I am creating the mongodb connection from main method and defer that open connection.
func main(){
session := db.CreateConnection(connectionStr)
defer session.Close()
}
The issue is I need to pass this sesstion object to user handler struct and from that pass to db handler.
type UserController struct {
DB DBOps
}
type DBOps struct {
session *mgo.Session
}
Question: How can we directly create the session object and inside db handler file and defer that when application closes ?
db.go
type DBOps struct {
session *mgo.Session
}
func (m *DBOps) Init(connectionstr string) error {
session, err := mgo.Dial(connectionstr)
// Check if connection error, is mongo running?
if err != nil {
panic(err)
}
}
inside main function I can just call
func main(){
db.Init(connectionstr);
}
but How to defer this session object on the main method ?