Skip to content

Commit

Permalink
Reverse the order of the middleware when they applied in gorilla/mux …
Browse files Browse the repository at this point in the history
…implementation (oapi-codegen#842)

* Reverse the order of the middleware when they apopted in gorilla/mux implementation

* Add config to keep compatibility

* Rename option by omitting
  • Loading branch information
mpls104 authored Dec 17, 2022
1 parent e1b4ade commit ab90f19
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 8 deletions.
2 changes: 2 additions & 0 deletions examples/petstore-expanded/gorilla/api/cfg.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ generate:
models: true
embedded-spec: true
output: petstore.gen.go
compatibility:
apply-gorilla-middleware-first-to-last: true
16 changes: 8 additions & 8 deletions examples/petstore-expanded/gorilla/api/petstore.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions pkg/codegen/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ type CompatibilityOptions struct {
// This resolves the behavior such that middlewares are chained in the order they are invoked.
// Please see https://github.com/deepmap/oapi-codegen/issues/786
ApplyChiMiddlewareFirstToLast bool `yaml:"apply-chi-middleware-first-to-last,omitempty"`
// Our generated code for gorilla/mux has historically inverted the order in which gorilla/mux middleware is
// applied such that the last invoked middleware ends up executing first in the middlewares chain
// This resolves the behavior such that middlewares are chained in the order they are invoked.
// Please see https://github.com/deepmap/oapi-codegen/issues/841
ApplyGorillaMiddlewareFirstToLast bool `yaml:"apply-gorilla-middleware-first-to-last,omitempty"`
}

// OutputOptions are used to modify the output code in some way.
Expand Down
6 changes: 6 additions & 0 deletions pkg/codegen/templates/gorilla/gorilla-middleware.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,15 @@ func (siw *ServerInterfaceWrapper) {{$opid}}(w http.ResponseWriter, r *http.Requ
siw.Handler.{{.OperationId}}(w, r{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}})
}

{{if opts.Compatibility.ApplyGorillaMiddlewareFirstToLast}}
for i := len(siw.HandlerMiddlewares) -1; i >= 0; i-- {
handler = siw.HandlerMiddlewares[i](handler)
}
{{else}}
for _, middleware := range siw.HandlerMiddlewares {
handler = middleware(handler)
}
{{end}}

handler(w, r.WithContext(ctx))
}
Expand Down

0 comments on commit ab90f19

Please sign in to comment.