oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Chi middleware wrapping logic executes the beginning middlewares at the later part

Open juddbaguio opened this issue 2 years ago • 2 comments

Current implementation server middlewares to a handler goes like this:

var handler = func(w http.ResponseWriter, r *http.Request) {
	siw.Handler.YourRouteHandler(w, r)
}

for _, middleware := range siw.HandlerMiddlewares {
	handler = middleware(handler)
}

The snippet above tends to execute beginning middlewares at the later than the last ones.

The looping is supposed to be like this:

var handler = func(w http.ResponseWriter, r *http.Request) {
	siw.Handler.YourRouteHandler(w, r)
}

for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i--  {
	h := siw.HandlerMiddlewares[i]
        if h != nil {
          handler = h(handler)
        }
}

The solution is referenced from Ardan Lab's Service repository on wrapping middlewares

juddbaguio avatar Jul 20 '22 00:07 juddbaguio

Here is the source from chi:

// chain builds a http.Handler composed of an inline middleware stack and endpoint
// handler in the order they are passed.
func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
	// Return ahead of time if there aren't any middlewares for the chain
	if len(middlewares) == 0 {
		return endpoint
	}


	// Wrap the end handler with the middleware chain
	h := middlewares[len(middlewares)-1](endpoint)
	for i := len(middlewares) - 2; i >= 0; i-- {
		h = middlewares[i](h)
	}


	return h
}

https://github.com/go-chi/chi/blob/9db25e5b381fbd6350583b857e74ecaffe355819/chain.go#L34-L49

chanced avatar Aug 05 '22 05:08 chanced

This should now be supported in the next release (including this PR) using the following options in your config YAML:

compatibility:
  apply-chi-middleware-first-to-last: true

This issue can be closed (but I don't have permissions to close it).

ericvolp12 avatar Oct 22 '22 19:10 ericvolp12