Go Lang and Labix mgo - getting EOF after subsequent requests
I have a web process similar to
func main() {
// mgo
mongoDatabase, err := mgopath.Connect(envMongoPath)
if err != nil {
log.Fatal(err)
}
r := mux.NewRouter()
// ....
r.HandleFunc("/apps/{app:.+}", stuffHandler(mongoDatabase)).Methods("GET")
http.Handle("/", r)
listen := fmt.Sprintf("%s:%s", host, port)
log.Fatal(http.ListenAndServe(listen, nil))
}
while mgopath.Connect looks like
func Connect(mongoPath string) (*mgo.Database, error) {
dbConfig, err := url.Parse(mongoPath)
if err != nil {
return nil, err
}
log.Printf("Connecting to %s", dbConfig.Host)
sess, err := mgo.Dial(dbConfig.Host)
if err != nil {
return nil, err
}
dbName := dbConfig.Path
log.Printf("Using database %s", dbName)
if len(dbName) < 2 {
return nil, errors.New("No database name specified.")
}
dbName = dbConfig.Path[1:len(dbConfig.Path)]
return sess.DB(dbName), err
}
Somewhere along the road:
c := database.C("stuff")
err = c.Find(bson.M{"id": id}).One(&item) // First ~1-2 minutes work as expected, then I receive EOFs
// c.Insert(), c.Update(), c.All()...
The problem is that after a couple of minutes, all requests to mongodb return an error EOF
. I have to restart the process in order to work again. Experiencing both problems on Mac and (more often) Windows. MongoDB runs inside Docker, which in turn runs inside boot2docker. VM port forwarding has been done (so requests take a certain amount of time).
Do I need to require me to dial the number every time I make a request? Is there some kind of timeout that I am not aware of?
source to share
The answer can be found here: https://groups.google.com/forum/#!topic/mgo-users/XM0rc6p-V-8
There are two easy ways to get rid of the error:
1) Refresh the call on the session, which causes it to abandon (or bring back the pool if the connection is good), the connection it holds, and select a new one if necessary.
2) Instead of using a single session, use many calls to session.Copy when you need a new session, then call session.Close when you're with that. This also means that you are using multiple connections to the database as needed.
source to share