How to store and get a pointer reference in a global scope in GO -
i have got follow code:
package main func main() { // create pointer referece of session of mongo db session := mongodb.createsession() // question 1 : how store pointer reference in global scope , using anywhere of code defer session.close() // note suppose code call handler methods call process in package controller(the last 1 code) }
code of creating session of mongodb
package mongodb func createsession() *mgo.session { session, err := mgo.dial("192.168.0.108:27017/databasename") if err != nil { panic(err) } session.setmode(mgo.monotonic, true) return session }
place want use pointer reference store in main
package controller func process() { // question 2 : how can pointer reference store in question 1 if posible collection := mongodb.createcollection(session, "namedatabase", "colectiondata") mongodb.insertdata(collection, "ale", "45646565") }
the idea avoid passing reference session(my pointer reference in main function) in every 1 of functions created project.
you can't have controller
package import main
. not idea (and quite sure not possible). doesn't mean can't have global session
variable in controller
.
you can try this:
package main import ( "controller" "mongodb" ) func main() { // create pointer referece of session of mongo db session := mongodb.createsession() defer session.close() controller.setdbsession(session) // or controller.init or whatever controller.process() }
and in controller
package have:
package controller import "mongodb" // global session var package var session mongodb.session // setdbsession sets mongodb session used controller package. // function must called before calling process() func setdbsession(s mongodb.session) { session = s } func process() { collection := mongodb.createcollection(session, "namedatabase", "colectiondata") mongodb.insertdata(collection, "ale", "45646565") }
using solution, have pass session controller package once, letting main take care of creating , closing of session.
Comments
Post a Comment