Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know if a mgo session is closed

Tags:

mongodb

go

mgo

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.

like image 621
xjpsjtu Avatar asked Oct 17 '18 07:10

xjpsjtu


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.

like image 70
icza Avatar answered Oct 05 '22 20:10

icza