I have created a mongo package which is suppose to create a connection and reuse this connection every time I need a connection. But everytime I call Session(), the session variable is nil and it creates a new connection to DB.
package mongo
import (
"fmt"
"github.com/globalsign/mgo"
"os"
)
var url = os.Getenv("MONGO_DB")
var session *mgo.Session
func Session() *mgo.Session {
fmt.Println(session)
if session == nil {
if url == "" {
url = "mongodb://localhost:27017/"
}
session, _ := mgo.Dial(url)
fmt.Println("Mongo Connected")
return session
}
defer session.Close()
return session
}
func GetUserById(Id string) UserModel {
posts := Session().DB("app").C("users")
user := UserModel{}
posts.Find(bson.M{"_id": bson.ObjectIdHex(Id)}).One(&user)
fmt.Printf("Mongo Query return for User %+v\n", user)
return user
}