I am trying to connect Go application with MongoDB server while running the database using docker.
I'm able to connect to the DB using the shell and perform different actions. However, the Go app fails when connecting to the DB. I'm using mgo driver and below is the code in use where am trying to implement a db middleware that can be used by all routes:
middleware code:
package db
import (
"net/http"
"os"
"github.com/gorilla/context"
"github.com/urfave/negroni"
mgo "gopkg.in/mgo.v2"
)
const key = "dbkey"
func GetDb(r *http.Request) *mgo.Database {
if rv := context.Get(r, key); rv != nil {
return rv.(*mgo.Database)
}
return nil
}
func SetDb(r *http.Request, val *mgo.Database) {
context.Set(r, key, val)
}
func MongoMiddleware() negroni.HandlerFunc {
database := os.Getenv("DB_NAME")
session, err := mgo.Dial("127.0.0.1:27017")
if err != nil {
println(err) // error message below
}
return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
reqSession := session.Clone()
defer reqSession.Close()
db := reqSession.DB(database)
SetDb(r, db)
next(rw, r)
})
}
the error am getting is :
panic: runtime error: invalid memory address or nil pointer dereference
route and main package code:
package main
import (
gmux "github.com/gorilla/mux"
"github.com/urfave/negroni"
"github.com/mypro/db"
"github.com/mypro/hub"
)
func main() {
router := gmux.NewRouter()
router.HandleFunc("/name", hub.Create).
Methods("GET")
n := negroni.Classic()
n.Use(db.MongoMiddleware())
n.UseHandler(router)
n.Run(":9000")
}
method that consume the db middleware to find a collection:
type Name struct {
Id bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
}
func Create(w http.ResponseWriter, r *http.Request) {
var aName Name
db := db.GetDb(r)
names := db.C("x")
err := names.Find(bson.M{"name": "sam"}).One(&aName)
if err != nil {
log.Print(err)
}
fmt.Println(&aName)
json.NewEncoder(w).Encode(&aName)
}