tsweb: Add MiddlewareStack func to apply lists of Middleware (#12907)
Fixes #12909 Signed-off-by: Paul Scott <paul@tailscale.com>
This commit is contained in:
@@ -372,6 +372,34 @@ type ReturnHandlerFunc func(http.ResponseWriter, *http.Request) error
|
||||
// request to the underlying handler, if appropriate.
|
||||
type Middleware func(h http.Handler) http.Handler
|
||||
|
||||
// MiddlewareStack combines multiple middleware into a single middleware for
|
||||
// decorating a [http.Handler]. The first middleware argument will be the first
|
||||
// to process an incoming request, before passing the request onto subsequent
|
||||
// middleware and eventually the wrapped handler.
|
||||
//
|
||||
// For example:
|
||||
//
|
||||
// MiddlewareStack(A, B)(h).ServeHTTP(w, r)
|
||||
//
|
||||
// calls in sequence:
|
||||
//
|
||||
// a.ServeHTTP(w, r)
|
||||
// -> b.ServeHTTP(w, r)
|
||||
// -> h.ServeHTTP(w, r)
|
||||
//
|
||||
// (where the lowercase handlers were generated by the uppercase middleware).
|
||||
func MiddlewareStack(mw ...Middleware) Middleware {
|
||||
if len(mw) == 1 {
|
||||
return mw[0]
|
||||
}
|
||||
return func(h http.Handler) http.Handler {
|
||||
for i := len(mw) - 1; i >= 0; i-- {
|
||||
h = mw[i](h)
|
||||
}
|
||||
return h
|
||||
}
|
||||
}
|
||||
|
||||
// ServeHTTPReturn calls f(w, r).
|
||||
func (f ReturnHandlerFunc) ServeHTTPReturn(w http.ResponseWriter, r *http.Request) error {
|
||||
return f(w, r)
|
||||
|
||||
Reference in New Issue
Block a user