Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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")
}
@bwghughes

This comment has been minimized.

Copy link

@bwghughes bwghughes commented Jul 9, 2014

Excellent work my friend :)

@muei

This comment has been minimized.

Copy link

@muei muei commented Sep 2, 2014

How about mysql?

@dej4vu

This comment has been minimized.

Copy link

@dej4vu dej4vu commented Oct 12, 2014

nice job

@alexcrownus

This comment has been minimized.

Copy link

@alexcrownus alexcrownus commented Mar 20, 2015

use n.UseHandler(context.ClearHandler(mux)) on line 80 to avoid memory leak

@mehakdeep

This comment has been minimized.

Copy link

@mehakdeep mehakdeep commented Aug 26, 2015

@Adesegun thanks that was very important point.

@d3sire

This comment has been minimized.

Copy link

@d3sire d3sire commented May 27, 2016

Why doesn't defer reqSession.Close() in the middleware closes the session before handler can use it?

@nathanmalishev

This comment has been minimized.

Copy link

@nathanmalishev nathanmalishev commented Oct 8, 2017

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