-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.go
107 lines (89 loc) · 2.2 KB
/
mux.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
104
105
106
107
package pi
import (
"errors"
"net/http"
"net/url"
"sync"
)
var defaultNotFoundHandler HandlerFunc = func(ctx Context) error {
return ctx.Code(404)
}
var defaultErrorFormatter = func(ctx Context, err error) {
ctx.Error(http.StatusInternalServerError, &ErrorResult{
Error: "unknown",
ErrorMessage: err.Error(),
})
}
type ServerMux interface {
http.Handler
Route(path string) Route
Group(prefix string, fn func(sm ServerMux))
SetNotFoundHandler(h HandlerFunc)
SetErrorFormatter(fn func(ctx Context, err error))
Use(c func(next HandlerFunc) HandlerFunc)
}
var _ ServerMux = (*servermux)(nil)
type servermux struct {
notFoundHandler HandlerFunc
root *_route
capcap *sync.Pool
errorFormater func(ctx Context, err error)
prefix string
cc []func(next HandlerFunc) HandlerFunc
}
func NewServerMux() ServerMux {
return &servermux{
root: createRootRoute(),
notFoundHandler: defaultNotFoundHandler,
errorFormater: defaultErrorFormatter,
capcap: &sync.Pool{
New: func() any {
return make(url.Values)
},
},
}
}
func (sm *servermux) SetErrorFormatter(fn func(ctx Context, err error)) {
sm.errorFormater = fn
}
func (sm *servermux) SetNotFoundHandler(h HandlerFunc) {
sm.notFoundHandler = h
}
func (sm *servermux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cap := sm.capcap.Get().(url.Values)
defer func() {
for k := range cap {
cap[k] = cap[k][:0] // reset slice to empty, but the keys in map will keep
}
sm.capcap.Put(cap)
}()
ctx := createContext(w, r, cap)
var err error
n := sm.root.Search(r.URL.Path, cap) // 1 allocs/op
if n == nil {
err = ErrHandlerNotFound
} else {
// 2 allocs/op
err = n.Invoke(ctx)
}
if errors.Is(err, ErrHandlerNotFound) {
err = sm.notFoundHandler(ctx)
}
if err != nil {
sm.errorFormater(ctx, err)
}
}
func (sm *servermux) Route(path string) Route {
return sm.root.Insert(sm.prefix+path, sm.cc...)
}
func (sm *servermux) Group(prefix string, fn func(sm ServerMux)) {
prev := sm.prefix
prevCC := sm.cc
sm.prefix = sm.prefix + prefix
fn(sm)
sm.prefix = prev
sm.cc = prevCC
}
func (sm *servermux) Use(c func(next HandlerFunc) HandlerFunc) {
sm.cc = append(sm.cc, c)
}