1
votes
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:[email protected]:27017/")
    session.SetMode(mgo.Monotonic, true)
    c = session.DB("database").C("igData")
    fmt.Printf("Starting %v\n", 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:[email protected]:27017/")

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

Regards

1
Don't ignore the error returned by mgo.Dial().icza
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

1 Answers

2
votes

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

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