Skip to content

Instantly share code, notes, and snippets.

@Bochenski
Created July 9, 2014 14:41
Show Gist options
  • Save Bochenski/253dbc8c077599d234c3 to your computer and use it in GitHub Desktop.
Save Bochenski/253dbc8c077599d234c3 to your computer and use it in GitHub Desktop.
Negroni golang mgo middleware example
package main
import (
"github.com/codegangsta/negroni"
"github.com/gorilla/context"
"github.com/unrolled/render"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"log"
"net/http"
"os"
)
type key int
const db key = 0
func GetDb(r *http.Request) *mgo.Database {
if rv := context.Get(r, db); rv != nil {
return rv.(*mgo.Database)
}
return nil
}
func SetDb(r *http.Request, val *mgo.Database) {
context.Set(r, db, val)
}
type Site struct {
Env string
Id bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
}
func getSite(db *mgo.Database) *Site {
var aSite Site
sites := db.C("COLLECTION__NAME")
err := sites.Find(bson.M{"name": "some site name"}).One(&aSite)
if err != nil {
log.Print(err)
}
aSite.Env = os.Getenv("APP_ENV")
return &aSite
}
func MongoMiddleware() negroni.HandlerFunc {
database := os.Getenv("DB_NAME")
session, err := mgo.Dial("127.0.0.1:27017")
if err != nil {
panic(err)
}
return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
reqSession := session.Clone()
defer reqSession.Close()
db := reqSession.DB(database)
SetDb(r, db)
next(rw, r)
})
}
func main() {
r := render.New(render.Options{
Layout: "index",
Delims: render.Delims{"[[", "]]"},
})
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
db := GetDb(req)
site := getSite(db)
r.HTML(w, http.StatusOK, "home", site)
})
n := negroni.Classic()
n.Use(MongoMiddleware())
n.UseHandler(mux)
n.Run(":3200")
}
@nathanmalishev
Copy link

Should line 49 be somehow moved from to main -- Does calling mgo.Dial per request affect performance? Or is this somehow cached away.

From mgo Dial DocumentationThis method is generally called just once for a given cluster. Further sessions to the same cluster are then established using the New or Copy methods on the obtained session. This will make them share the underlying cluster, and manage the pool of connections appropriately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment