-
Notifications
You must be signed in to change notification settings - Fork 14
/
allowed_methods.go
77 lines (65 loc) · 1.76 KB
/
allowed_methods.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
package middleware
import (
"net/http"
"strings"
)
var DefaultFileSpaAllowedMethods = []string{
http.MethodGet,
http.MethodHead,
}
var DefaultEndpointAllowedMethods = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodOptions,
}
var _ http.Handler = &AllowedMethodsHandler{}
type AllowedMethodsHandler struct {
allowedMethods map[string]struct{}
allowedHandler http.Handler
notAllowedHandler http.Handler
}
type methodAllowedFunc func(string) bool
func NewAllowedMethodsHandler(allowedMethods, defaultAllowedMethods []string, allowedHandler, notAllowedHandler http.Handler) *AllowedMethodsHandler {
amh := &AllowedMethodsHandler{
allowedMethods: make(map[string]struct{}),
allowedHandler: allowedHandler,
notAllowedHandler: notAllowedHandler,
}
if allowedMethods == nil && defaultAllowedMethods != nil {
allowedMethods = defaultAllowedMethods
}
for _, method := range allowedMethods {
if method == "*" {
if defaultAllowedMethods == nil {
continue
}
for _, m := range defaultAllowedMethods {
amh.allowedMethods[m] = struct{}{}
}
} else {
method = strings.ToUpper(method)
amh.allowedMethods[method] = struct{}{}
}
}
return amh
}
func (a *AllowedMethodsHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
method := strings.ToUpper(req.Method)
if _, ok := a.allowedMethods[method]; !ok {
a.notAllowedHandler.ServeHTTP(rw, req)
return
}
a.allowedHandler.ServeHTTP(rw, req)
}
func (a *AllowedMethodsHandler) MethodAllowed(method string) bool {
method = strings.TrimSpace(strings.ToUpper(method))
_, ok := a.allowedMethods[method]
return ok
}
func (a *AllowedMethodsHandler) Child() http.Handler {
return a.allowedHandler
}