Last active
December 31, 2015 07:39
-
-
Save rday/7955211 to your computer and use it in GitHub Desktop.
Brief example of an application specific context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Struct to hold all my application's commonly used packages | |
type MySpecialContext struct { | |
Render render.Render | |
Logger *log.Logger | |
Session sessions.Session | |
Db *mgo.Database | |
Ctx martini.Context | |
App *ApplicationConfig | |
} | |
// Wrapper to be called by m.Use(). This will .Map our special context | |
// into the Martini context. Then our handlers will only have to use | |
// the MySpecialContext struct to access all the other variables | |
func ContextWrapper(cfg *ApplicationConfig) martini.Handler { | |
return func(c martini.Context, l *log.Logger, s sessions.Session, db *mgo.Database, r render.Render) { | |
var ctx = MySpecialContext{r, l, s, db, c, cfg} | |
c.Map(ctx) | |
} | |
} | |
// Quick example of using MySpecialContext | |
func index(c MySpecialContext) { | |
c.Logger.Println("Here we are") | |
c.Render.HTML(200, "index", nil) | |
} | |
func main() { | |
m := martini.Classic() | |
// m.Use(AllTheThings) | |
m.Use(ContextWrapper(myAppConfig)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment