I\'m currently using a mongodb with mgo lib for a web application, but I\'m not sure if the way I\'m using it, is good one ..
package db
import (
\"gopk
With go 1.7, the most idiomatic way of handling mongo session on a webserver is to use the new standard library package context to write a middleware that can attach the defer session.Close() to whenever the request context Done() is called. So you do not need to remeber to close
AttachDeviceCollection = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
db, err := infra.Cloner()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
collection, err := NewDeviceCollection(db)
if err != nil {
db.Session.Close()
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ctx := context.WithValue(r.Context(), DeviceRepoKey, collection)
go func() {
select {
case <-ctx.Done():
collection.Session.Close()
}
}()
next.ServeHTTP(w, r.WithContext(ctx))
})
}