0

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
}
Ashok Kumar Sahoo
  • 580
  • 3
  • 8
  • 24
  • Simply store the `mgo.Session` in a global var, and use that (it's safe for concurrent use), or optionally copy / clone it when needed, and close the copy when not needed anymore. – icza Nov 09 '18 at 09:30
  • Also related: [too many open files in mgo go server](https://stackoverflow.com/questions/47179890/too-many-open-files-in-mgo-go-server/47180097#47180097); and [Concurrency in gopkg.in/mgo.v2 (Mongo, Go)](https://stackoverflow.com/questions/42492020/concurrency-in-gopkg-in-mgo-v2-mongo-go/42495522#42495522). – icza Nov 09 '18 at 10:12

0 Answers0