Skip to content

Instantly share code, notes, and snippets.

@pagreczner
Last active August 9, 2016 08:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pagreczner/227913794e096953972c to your computer and use it in GitHub Desktop.
Save pagreczner/227913794e096953972c to your computer and use it in GitHub Desktop.
Negroni and Gorilla Mux with Middleware example - golang
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)
}
@ijonas
Copy link

ijonas commented Apr 20, 2016

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