Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adpat http middleware handler to filter #504

Closed
ggicci opened this issue Jul 20, 2022 · 1 comment
Closed

Adpat http middleware handler to filter #504

ggicci opened this issue Jul 20, 2022 · 1 comment

Comments

@ggicci
Copy link
Contributor

ggicci commented Jul 20, 2022

Let's treat the following signature as an "http middleware handler":

type HttpMiddlewareHandler func(http.Handler) http.Handler

I believe many of us are implementing middleware functions in this way. It's really easy to chain these kind of handlers together to work as one complete http handler. And there are already many middleware functions in the community implemented this way. Here are some packages or frameworks supporting this:

  1. https://github.com/justinas/alice
  2. https://github.com/gorilla/handlers
  3. https://github.com/go-chi/chi/tree/master/middleware
  4. ...

In go-restful, we can find an easy way to turn such a middleware handler to a filter. It should work like a charm.

Here's my proposal of the API:

// Adapts a middleware handler to a filter.
func HttpMiddlewareHandlerToFilter(middleware HttpMiddlewareHandler) FilterFunction { ... }

// Usage Demo
//
// Sample middleware handler, for authentication.
func auth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Authorization") != "admin" {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}

		next.ServeHTTP(w, r)
	})
}

ws := new(WebService)
ws.Route(ws.GET("/users").Filter(
	HttpMiddlewareHandlerToFilter(auth),
).To(listUsers))
@ggicci
Copy link
Contributor Author

ggicci commented Jul 21, 2022

Similar discussion from iris community: kataras/iris#1885

@ggicci ggicci closed this as completed Jul 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant