Best practice to maintain a mgo session

后端 未结 3 990
感动是毒
感动是毒 2020-11-27 14:03

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         


        
3条回答
  •  情歌与酒
    2020-11-27 14:54

    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))
            })
        }
    

提交回复
热议问题