...
1 package chi
2
3 import "net/http"
4
5
6 func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares {
7 return Middlewares(middlewares)
8 }
9
10
11
12 func (mws Middlewares) Handler(h http.Handler) http.Handler {
13 return &ChainHandler{mws, h, chain(mws, h)}
14 }
15
16
17
18 func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler {
19 return &ChainHandler{mws, h, chain(mws, h)}
20 }
21
22
23
24 type ChainHandler struct {
25 Middlewares Middlewares
26 Endpoint http.Handler
27 chain http.Handler
28 }
29
30 func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
31 c.chain.ServeHTTP(w, r)
32 }
33
34
35
36 func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
37
38 if len(middlewares) == 0 {
39 return endpoint
40 }
41
42
43 h := middlewares[len(middlewares)-1](endpoint)
44 for i := len(middlewares) - 2; i >= 0; i-- {
45 h = middlewares[i](h)
46 }
47
48 return h
49 }
50
View as plain text