-
Notifications
You must be signed in to change notification settings - Fork 0
/
method_handler.go
78 lines (69 loc) · 1.52 KB
/
method_handler.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
package httpmux
import (
"net/http"
"sort"
"strings"
)
type methodHandler struct {
all http.Handler
methods map[string]http.Handler
}
func newMethodHandler() *methodHandler {
return &methodHandler{}
}
func (mh *methodHandler) put(handler http.Handler, methods ...string) {
if len(methods) == 0 {
mh.all = handler
return
}
if mh.methods == nil {
mh.methods = map[string]http.Handler{}
}
for _, method := range cleanMethods(methods) {
if handler == nil {
delete(mh.methods, method)
} else {
mh.methods[method] = handler
}
}
}
func (mh *methodHandler) get(cleanedMethod string) (http.Handler, error) {
if mh == nil {
return nil, ErrNotFound
}
if len(mh.methods) == 0 {
if mh.all != nil {
return mh.all, nil
}
return nil, ErrNotFound
}
handler := mh.methods[cleanedMethod]
if handler != nil {
return handler, nil
}
if mh.all != nil {
return mh.all, nil
}
return nil, ErrMethodNotAllowed(mh.listMethods())
}
func (mh *methodHandler) isRegistered() bool {
return mh.all != nil || len(mh.methods) > 0
}
func (mh *methodHandler) listMethods() []string {
result := make([]string, 0, len(mh.methods))
for method, _ := range mh.methods {
result = append(result, method)
}
sort.Strings(result)
return result
}
func cleanMethods(methods []string) []string {
result := make([]string, 0, len(methods))
for _, method := range methods {
result = append(result, cleanMethod(method))
}
return result
}
func cleanMethod(method string) string {
return strings.TrimSpace(strings.ToUpper(method))
}