invalid memory address or nil pointer dereference with mgo












0















package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
)

type DataIg struct {
Member string `json:"Member"`
Timestamp float64 `json:"Timestamp"`
Name string `json:"Name"`
Bid string `json:"Bid"`
Offer string`json:"Offer"`
Change string `json:"Change"`
Hour string `json:"Hour"`
}

type Response struct {
Status string
}

var session *mgo.Session
var c *mgo.Collection

func postData(w http.ResponseWriter, r *http.Request) {
var response = Response{}
response.Status = "ok"
var reception = DataIg{}

err := c.Insert(reception)

body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(body, &reception)
fmt.Println(reception)
js, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(js)
}

var appName = "accountservice"

func main() {
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")
session.SetMode(mgo.Monotonic, true)
c = session.DB("database").C("igData")
fmt.Printf("Starting %vn", appName)
router := mux.NewRouter()
router.HandleFunc("/postData", postData).Methods("POST")
corsObj := handlers.AllowedOrigins(string{"*"})
http.ListenAndServe(":8066", handlers.CORS(corsObj)(router))
defer session.Close()
}


I am trying to make the session and the connection (c) global to use them in another function other than PostData.



But i have a :




panic: runtime error: invalid memory address or nil pointer
dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0
pc=0x683587]




here :
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")



I would like to have the collection on a global way to use it outside the main func.



Regards










share|improve this question




















  • 4





    Don't ignore the error returned by mgo.Dial().

    – icza
    Nov 15 '18 at 21:00











  • Any time you encounter an problem in Go, check to see if you're ignoring any errors anywhere around it, and stop ignoring them. There's a good chance the errors will explain what's going on.

    – Adrian
    Nov 15 '18 at 22:00


















0















package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
)

type DataIg struct {
Member string `json:"Member"`
Timestamp float64 `json:"Timestamp"`
Name string `json:"Name"`
Bid string `json:"Bid"`
Offer string`json:"Offer"`
Change string `json:"Change"`
Hour string `json:"Hour"`
}

type Response struct {
Status string
}

var session *mgo.Session
var c *mgo.Collection

func postData(w http.ResponseWriter, r *http.Request) {
var response = Response{}
response.Status = "ok"
var reception = DataIg{}

err := c.Insert(reception)

body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(body, &reception)
fmt.Println(reception)
js, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(js)
}

var appName = "accountservice"

func main() {
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")
session.SetMode(mgo.Monotonic, true)
c = session.DB("database").C("igData")
fmt.Printf("Starting %vn", appName)
router := mux.NewRouter()
router.HandleFunc("/postData", postData).Methods("POST")
corsObj := handlers.AllowedOrigins(string{"*"})
http.ListenAndServe(":8066", handlers.CORS(corsObj)(router))
defer session.Close()
}


I am trying to make the session and the connection (c) global to use them in another function other than PostData.



But i have a :




panic: runtime error: invalid memory address or nil pointer
dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0
pc=0x683587]




here :
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")



I would like to have the collection on a global way to use it outside the main func.



Regards










share|improve this question




















  • 4





    Don't ignore the error returned by mgo.Dial().

    – icza
    Nov 15 '18 at 21:00











  • Any time you encounter an problem in Go, check to see if you're ignoring any errors anywhere around it, and stop ignoring them. There's a good chance the errors will explain what's going on.

    – Adrian
    Nov 15 '18 at 22:00
















0












0








0








package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
)

type DataIg struct {
Member string `json:"Member"`
Timestamp float64 `json:"Timestamp"`
Name string `json:"Name"`
Bid string `json:"Bid"`
Offer string`json:"Offer"`
Change string `json:"Change"`
Hour string `json:"Hour"`
}

type Response struct {
Status string
}

var session *mgo.Session
var c *mgo.Collection

func postData(w http.ResponseWriter, r *http.Request) {
var response = Response{}
response.Status = "ok"
var reception = DataIg{}

err := c.Insert(reception)

body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(body, &reception)
fmt.Println(reception)
js, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(js)
}

var appName = "accountservice"

func main() {
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")
session.SetMode(mgo.Monotonic, true)
c = session.DB("database").C("igData")
fmt.Printf("Starting %vn", appName)
router := mux.NewRouter()
router.HandleFunc("/postData", postData).Methods("POST")
corsObj := handlers.AllowedOrigins(string{"*"})
http.ListenAndServe(":8066", handlers.CORS(corsObj)(router))
defer session.Close()
}


I am trying to make the session and the connection (c) global to use them in another function other than PostData.



But i have a :




panic: runtime error: invalid memory address or nil pointer
dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0
pc=0x683587]




here :
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")



I would like to have the collection on a global way to use it outside the main func.



Regards










share|improve this question
















package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
)

type DataIg struct {
Member string `json:"Member"`
Timestamp float64 `json:"Timestamp"`
Name string `json:"Name"`
Bid string `json:"Bid"`
Offer string`json:"Offer"`
Change string `json:"Change"`
Hour string `json:"Hour"`
}

type Response struct {
Status string
}

var session *mgo.Session
var c *mgo.Collection

func postData(w http.ResponseWriter, r *http.Request) {
var response = Response{}
response.Status = "ok"
var reception = DataIg{}

err := c.Insert(reception)

body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
err = json.Unmarshal(body, &reception)
fmt.Println(reception)
js, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(js)
}

var appName = "accountservice"

func main() {
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")
session.SetMode(mgo.Monotonic, true)
c = session.DB("database").C("igData")
fmt.Printf("Starting %vn", appName)
router := mux.NewRouter()
router.HandleFunc("/postData", postData).Methods("POST")
corsObj := handlers.AllowedOrigins(string{"*"})
http.ListenAndServe(":8066", handlers.CORS(corsObj)(router))
defer session.Close()
}


I am trying to make the session and the connection (c) global to use them in another function other than PostData.



But i have a :




panic: runtime error: invalid memory address or nil pointer
dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0
pc=0x683587]




here :
session, _ := mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/")



I would like to have the collection on a global way to use it outside the main func.



Regards







go mgo






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 21:25







user462794

















asked Nov 15 '18 at 20:43









user462794user462794

25431951




25431951








  • 4





    Don't ignore the error returned by mgo.Dial().

    – icza
    Nov 15 '18 at 21:00











  • Any time you encounter an problem in Go, check to see if you're ignoring any errors anywhere around it, and stop ignoring them. There's a good chance the errors will explain what's going on.

    – Adrian
    Nov 15 '18 at 22:00
















  • 4





    Don't ignore the error returned by mgo.Dial().

    – icza
    Nov 15 '18 at 21:00











  • Any time you encounter an problem in Go, check to see if you're ignoring any errors anywhere around it, and stop ignoring them. There's a good chance the errors will explain what's going on.

    – Adrian
    Nov 15 '18 at 22:00










4




4





Don't ignore the error returned by mgo.Dial().

– icza
Nov 15 '18 at 21:00





Don't ignore the error returned by mgo.Dial().

– icza
Nov 15 '18 at 21:00













Any time you encounter an problem in Go, check to see if you're ignoring any errors anywhere around it, and stop ignoring them. There's a good chance the errors will explain what's going on.

– Adrian
Nov 15 '18 at 22:00







Any time you encounter an problem in Go, check to see if you're ignoring any errors anywhere around it, and stop ignoring them. There's a good chance the errors will explain what's going on.

– Adrian
Nov 15 '18 at 22:00














1 Answer
1






active

oldest

votes


















1














I haven't used mgo extensively, however I can tell you that ignoring the error from session, _ = mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/") is a bad idea.



It's likely that session is nil because the returned err is set.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53327623%2finvalid-memory-address-or-nil-pointer-dereference-with-mgo%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I haven't used mgo extensively, however I can tell you that ignoring the error from session, _ = mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/") is a bad idea.



    It's likely that session is nil because the returned err is set.






    share|improve this answer




























      1














      I haven't used mgo extensively, however I can tell you that ignoring the error from session, _ = mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/") is a bad idea.



      It's likely that session is nil because the returned err is set.






      share|improve this answer


























        1












        1








        1







        I haven't used mgo extensively, however I can tell you that ignoring the error from session, _ = mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/") is a bad idea.



        It's likely that session is nil because the returned err is set.






        share|improve this answer













        I haven't used mgo extensively, however I can tell you that ignoring the error from session, _ = mgo.Dial("mongodb://toto:titib@56.39.92.666:27017/") is a bad idea.



        It's likely that session is nil because the returned err is set.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 15 '18 at 21:09









        poypoy

        6,53763365




        6,53763365
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53327623%2finvalid-memory-address-or-nil-pointer-dereference-with-mgo%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            The Sandy Post

            Danny Elfman

            Pages that link to "Head v. Amoskeag Manufacturing Co."