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.
1 Answers
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.

- 389,944
- 63
- 907
- 827
-
mgo provides [Session.Ping](https://godoc.org/github.com/globalsign/mgo#Session.Ping) to test if connectivity is available in the session. – Adrian Oct 17 '18 at 13:38
-
@Adrian Yes, but `Ping()` is to check connectivity, and asker wants to detect if `Session.Close()` was called before. It if was, quoting from its doc: _"It's a runtime error to use a session after it has been closed."_ So `Session.Ping()` should (may) also panic. – icza Oct 17 '18 at 13:42