justinas / alice

Painless middleware chaining for Go

Home Page:https://godoc.org/github.com/justinas/alice

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use with httprouter

byrnedo opened this issue · comments

Hi, I love alice and it works great alongside github.com/julienschmidt/httprouter until I need to do a per route middleware.

        authChain := alice.New(
		rest.CorrellationMiddleware, 
		rest.LogMiddleware(log),
		rest.TimeoutMiddleware, 
		rest.JwtAuthenticationMiddleware(pubKey)
	);
	noAuthChain := alice.New(
		rest.CorrellationMiddleware, 
		rest.LogMiddleware(log),
		rest.TimeoutMiddleware
	);

	router.POST("/auth/login", noAuthChain.ThenFunc(userController.Authenticate))
	router.GET("/users/me", authChain.ThenFunc(userController.Me))

This wont work since Httprouter requires a signature of (w http.ResponseWriter, r *http.Request, _ httprouter.Params) as a handler
Is there some way to get this to work even though?

Make a wrapper that gets http.Handler or http.HandlerFunc and returns func (http.ResponseWriter, *http.Request, httprouter.Params), f.e.:

func wrap(f http.HandlerFunc) func (http.ResponseWriter, *http.Request, httprouter.Params) {
	return func (w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		_ = p
		f(w, r)
	}
}