Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@itarato
Created November 10, 2014 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itarato/ab6ef5ad8c09f87132bf to your computer and use it in GitHub Desktop.
Save itarato/ab6ef5ad8c09f87132bf to your computer and use it in GitHub Desktop.
Simple controller backed up with MongoDB support.
package controllers
import (
"github.com/revel/revel"
"gopkg.in/mgo.v2"
)
type AppCtrl struct {
*revel.Controller
mongoSession *mgo.Session
mongoDatabase *mgo.Database
}
func (ctrl AppCtrl) GetMongoSession() *mgo.Session {
if ctrl.mongoSession == nil {
host := revel.Config.StringDefault("mongo.host", "localhost")
port := revel.Config.StringDefault("mongo.port", "27017")
var err error
ctrl.mongoSession, err = mgo.Dial(host + ":" + port)
if err != nil {
panic(err)
}
}
return ctrl.mongoSession
}
func (ctrl AppCtrl) GetMongoDatabase() *mgo.Database {
session := ctrl.GetMongoSession()
databaseName := revel.Config.StringDefault("mongo.database", "")
return session.DB(databaseName)
}
func (ctrl AppCtrl) GetMongoCollection(collectionName string) *mgo.Collection {
return ctrl.GetMongoDatabase().C(collectionName)
}
func (ctrl AppCtrl) CloseMongoSession() {
ctrl.GetMongoSession().Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment