-
-
Save orbitalmedia/618e9218b5f0a66fe495d1b77d49d9ed to your computer and use it in GitHub Desktop.
Negroni and Gorilla Mux with Middleware example - golang
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
| package main | |
| import ( | |
| "github.com/codegangsta/negroni" | |
| "github.com/gorilla/mux" | |
| ) | |
| func main() { | |
| router := mux.NewRouter() | |
| apiV1 := router.PathPrefix("/api/v1").Subrouter() | |
| NegroniRouter(apiV1, "/api/v1", "/users/create", "POST", externalLib.CreateUser, externalAuthLib.Authorize) | |
| n := negroni.Classic() | |
| n.UseHandler(router) | |
| n.Run(":3000") | |
| } | |
| /* Generates a negroni handler for the route: | |
| pathType (base+string) | |
| which is handled by `f` and passed through | |
| middleware `mids` sequentially. | |
| ex: | |
| NegroniRoute(router, "/api/v1", "/users/update", "POST", UserUpdateHandler, LoggingMiddleware, AuthorizationMiddleware) | |
| */ | |
| func NegroniRoute(m *mux.Router, | |
| base string, | |
| path string, | |
| pathType string, | |
| f func(http.ResponseWriter, *http.Request), // Your Route Handler | |
| mids ...func(http.ResponseWriter, *http.Request, http.HandlerFunc) // Middlewares | |
| ) { | |
| _routes := mux.NewRouter() | |
| _routes.HandleFunc(base+path, f).Methods(pathType) | |
| _n := negroni.New() | |
| for i: range(mids) { | |
| _n.Use(negroni.HandlerFunc(mids[i])) | |
| } | |
| _n.UseHandler(_routes) | |
| m.Handle(path, _n) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment