I'm using *mgo.Session
of MongoDB driver labix_mgo
for Go, however I don't know if a session is closed. When I use a closed session, a runtime error will be raised. I want to skip the session copy if I know a session is closed.
First, the mgo
driver you are using: gopkg.in/mgo.v2
(hosted at https://github.com/go-mgo/mgo) is not maintained anymore. Instead use the community supported fork github.com/globalsign/mgo
, it has a backward compatible API.
mgo.Session
does not provide a way to detect if it has been closed (using its Session.Close()
method).
But you shouldn't depend on others closing the session you are using. The same code that obtains a session should be responsible to close it. Follow this simple principle, and you won't bump into problems of using a closed session.
For instance, if we take a web server as an example, obtain a session using Session.Copy()
(or Session.Clone()
) in the beginning of the request, and close the session (preferably with defer) in the same handler, in the same function. And just pass along this session to whoever needs it. They don't have to close it, they mustn't, that's the responsibility of the function that created it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With