Skip to content

Instantly share code, notes, and snippets.

@codegangsta
Created January 28, 2015 16:55
Show Gist options
  • Save codegangsta/bd7a8e9f6341d1887ba2 to your computer and use it in GitHub Desktop.
Save codegangsta/bd7a8e9f6341d1887ba2 to your computer and use it in GitHub Desktop.
package models
import (
"net/http"
"labix.org/v2/mgo"
)
type DB struct {
Database string
Session *mgo.Session
}
func NewDB(server string, database string) *DB {
session, err := mgo.Dial(server)
if err != nil {
panic(err)
}
return &DB{
Database: database,
Session: session,
}
}
// Default pages
func (db *DB) Pages() *Pages {
return NewPages(db.Session.DB(db.Database).C("pages"))
}
func (db *DB) Events() *Events {
return NewEvents(db.Session.DB(db.Database).C("events"))
}
func (db *DB) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
session := db.Session.Clone()
defer session.Close()
database := session.DB(db.Database)
// Map Dependencies
SetPages(r, NewPages(database.C("pages")))
SetEvents(r, NewEvents(database.C("events")))
next(rw, r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment