Last active
August 9, 2016 08:50
-
-
Save pagreczner/227913794e096953972c to your computer and use it in GitHub Desktop.
Negroni and Gorilla Mux with Middleware example - golang
This file contains 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) | |
} |
Thanks, this gist got me out of pickle.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Subroutes with Negroni and Gorilla/Mux do not play nicely with each other. Additionally, trying to get the example with middleware applied to a base
/admin
type of route to work with subroutes of/admin
would not work because the new router you create for the specific negroni middleware handler has a different path prefix than your global router you might pass in.The
NegroniRoute
method is explicit in definition of subroute path and extension and allows you to pass in variable length middleware to each route as needed.Note - Has not been tested for performance under large number of api routes.