-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmiddleware_wrapper.go
51 lines (40 loc) · 1.53 KB
/
middleware_wrapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package gimlet
import (
"net/http"
"github.com/evergreen-ci/negroni"
)
// WrapperMiddleware is convenience function to produce middlewares
// from functions that wrap http.HandlerFuncs.
func WrapperMiddleware(w HandlerFuncWrapper) Middleware { return w }
// HandlerFuncWrapper provides a way to define a middleware as a function
// rather than a type.
type HandlerFuncWrapper func(http.HandlerFunc) http.HandlerFunc
// ServeHTTP provides a gimlet.Middleware compatible shim for
// HandlerFuncWrapper-typed middlewares.
func (w HandlerFuncWrapper) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w(next)(rw, r)
}
// HandlerWrapper provides a way to define a middleware as a function
// rather than a type for improved interoperability with native
// tools.
type HandlerWrapper func(http.Handler) http.Handler
// ServeHTTP provides a gimlet.Middleware compatible shim for
// HandlerWrapper-typed middlewares.
func (w HandlerWrapper) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
w(next).ServeHTTP(rw, r)
}
// WrapperHandlerMiddleware is convenience function to produce middlewares
// from functions that wrap http.Handlers.
func WrapperHandlerMiddleware(w HandlerWrapper) Middleware { return w }
// MergeMiddleware combines a number of middleware into a single
// middleware instance.
func MergeMiddleware(mws ...Middleware) Middleware {
if len(mws) == 0 {
panic("must merge one or more middlewares")
}
n := negroni.New()
for _, m := range mws {
n.Use(m)
}
return negroni.Wrap(n)
}