forked from go-chi/chi
/
util.go
103 lines (88 loc) · 2.65 KB
/
util.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package chi
import (
"fmt"
"net/http"
"strings"
"golang.org/x/net/context"
)
// Build a chained chi.Handler from a list of middlewares
func chain(middlewares []interface{}, handlers ...interface{}) Handler {
// join a middleware stack with inline middlewares
mws := append(middlewares, handlers[:len(handlers)-1]...)
// request handler
handler := handlers[len(handlers)-1]
// Assert the types in the middleware chain
for _, mw := range mws {
assertMiddleware(mw)
}
// Set the request handler to a context handler type
var cxh Handler
switch t := handler.(type) {
default:
panic(fmt.Sprintf("chi: unsupported handler signature: %T", t))
case Handler:
cxh = t
case func(context.Context, http.ResponseWriter, *http.Request):
cxh = HandlerFunc(t)
case http.Handler:
cxh = HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
t.ServeHTTP(w, r)
})
case func(http.ResponseWriter, *http.Request):
cxh = HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
t(w, r)
})
}
// Return ahead of time if there aren't any middlewares for the chain
if len(mws) == 0 {
return cxh
}
// Wrap the end handler with the middleware chain
h := mwrap(mws[len(mws)-1])(cxh)
for i := len(mws) - 2; i >= 0; i-- {
f := mwrap(mws[i])
h = f(h)
}
return h
}
// Wrap http.Handler middleware to chi.Handler middlewares
func mwrap(middleware interface{}) func(Handler) Handler {
switch mw := middleware.(type) {
default:
panic(fmt.Sprintf("chi: unsupported handler signature: %T", mw))
case func(Handler) Handler:
return mw
case func(http.Handler) http.Handler:
return func(next Handler) Handler {
return HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
wfn := func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTPC(ctx, w, r)
}
mw(http.HandlerFunc(wfn)).ServeHTTP(w, r)
})
}
}
}
// Runtime type checking of the middleware signature
func assertMiddleware(middleware interface{}) interface{} {
switch t := middleware.(type) {
default:
panic(fmt.Sprintf("chi: unsupported middleware signature: %T", t))
case func(http.Handler) http.Handler:
case func(Handler) Handler:
}
return middleware
}
// Respond with just the allowed methods, as required by RFC2616 for
// 405 Method not allowed.
func methodNotAllowedHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
methods := make([]string, len(methodMap))
i := 0
for m := range methodMap {
methods[i] = m // still faster than append to array with capacity
i++
}
w.Header().Add("Allow", strings.Join(methods, ","))
w.WriteHeader(405)
w.Write([]byte(http.StatusText(405)))
}