Skip to content

Instantly share code, notes, and snippets.

@jonathaningram
Created July 1, 2015 04:33
Show Gist options
  • Save jonathaningram/a610813e63016d69a04c to your computer and use it in GitHub Desktop.
Save jonathaningram/a610813e63016d69a04c to your computer and use it in GitHub Desktop.
Example "injecting" services into a HTTP handler using gorilla.pat and negroni
package web
func contactHandler(
res http.ResponseWriter,
req *http.Request,
csrf csrf.TokenManager,
nodeRepository node.Repository,
) {
}
package web
import (
"github.com/codegangsta/negroni"
"github.com/goincremental/negroni-sessions"
"github.com/goincremental/negroni-sessions/cookiestore"
"github.com/gorilla/pat"
)
// init because this is app engine
func init() {
// create services
store := cookiestore.New([]byte(appConfig.Secret))
templateEngine := template.NewEngine()
userRepository := user.NewCachingRepository(user.NewMemoryRepository())
nodeRepository := node.NewCachingRepository(node.NewDatastoreRepository())
router := pat.New()
router.NewRoute().Methods("HEAD", "GET").PathPrefix("/contact").Handler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
session := sessions.GetSession(req)
contactHandler(
res,
req,
csrf.NewTokenManager(session),
nodeRepository,
)
// could use some sort of DI-type container too but haven't had a need yet
contactHandler(
res,
req,
container.Get("node_repository"), // the container can determine what "node_repository" implementation gets returned, maybe it can even lazy-create it
)
}))
n := negroni.New()
n.UseHandler(router)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment