Skip to content

Instantly share code, notes, and snippets.

@lordnynex
Forked from pagreczner/negroniGorillaMux.go
Created August 9, 2016 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lordnynex/ba6b6f02a163596ed74592ec2972cbf1 to your computer and use it in GitHub Desktop.
Save lordnynex/ba6b6f02a163596ed74592ec2972cbf1 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment