-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux.go
226 lines (185 loc) · 4.82 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package minimalmux
import (
"context"
"errors"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
type ServeMux struct {
tree *Node
mu sync.RWMutex
notFoundHandler http.HandlerFunc
}
type Route struct {
Method string
Pattern string
HandlerFunc http.HandlerFunc
PathParamMap map[string]string
}
func (r *Route) IsBlank() bool {
return r.HandlerFunc == nil
}
func (r *Route) setPathParams(pathParamMap map[string]string) {
r.PathParamMap = pathParamMap
}
func NewServeMux() *ServeMux {
return &ServeMux{
tree: &Node{},
notFoundHandler: http.NotFound,
}
}
const methodAll = "_all"
var methodSlice = []string{
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodDelete,
http.MethodHead,
http.MethodOptions,
http.MethodPatch,
http.MethodConnect,
http.MethodTrace,
}
// net/http method wrapper
func (sm *ServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
sm.handle(methodAll, pattern, handler)
}
type paramCtxKey int
const paramMapKey paramCtxKey = iota
func (sm *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
route := sm.tree.search(r.Method, path)
if route.IsBlank() {
sm.notFoundHandler(w, r)
return
}
ctx := context.WithValue(r.Context(), paramMapKey, route.PathParamMap)
req := r.WithContext(ctx)
route.HandlerFunc(w, req)
}
func (sm *ServeMux) Handle(pattern string, handler http.Handler) {
sm.handle(methodAll, pattern, handler.ServeHTTP)
}
func (sm *ServeMux) Handler(r *http.Request) (h http.Handler, pattern string) {
path := r.URL.Path
route := sm.tree.search(r.Method, path)
return route.HandlerFunc, route.Pattern
}
func GetParams(r *http.Request) map[string]string {
if v := r.Context().Value(paramMapKey); v != nil {
return v.(map[string]string)
}
return nil
}
// original method
func (sm *ServeMux) handle(method string, pattern string, handler func(http.ResponseWriter, *http.Request)) {
sm.mu.Lock()
defer sm.mu.Unlock()
if method == "" {
panic("http: invalid method")
}
if handler == nil {
panic("http: nil handler")
}
// duplicate check
r := sm.tree.search(method, pattern)
if r.Method == method && r.Pattern == pattern {
panic("http: duplicated registrations for " + method + " " + pattern)
}
if method == methodAll {
for _, m := range methodSlice {
// duplicate check
r := sm.tree.search(m, pattern)
if r.Method == m && r.Pattern == pattern {
panic("http: duplicated registrations for " + m + " " + pattern)
}
// insert
sm.tree.insert(m, pattern, Route{
Method: m,
Pattern: pattern,
HandlerFunc: handler,
})
}
return
}
sm.tree.insert(method, pattern, Route{
Method: method,
Pattern: pattern,
HandlerFunc: handler,
})
}
func (sm *ServeMux) Get(path string, handler http.HandlerFunc) {
sm.method(http.MethodGet, path, handler)
}
func (sm *ServeMux) Post(path string, handler http.HandlerFunc) {
sm.method(http.MethodPost, path, handler)
}
func (sm *ServeMux) Put(path string, handler http.HandlerFunc) {
sm.method(http.MethodPut, path, handler)
}
func (sm *ServeMux) Delete(path string, handler http.HandlerFunc) {
sm.method(http.MethodDelete, path, handler)
}
func (sm *ServeMux) Head(path string, handler http.HandlerFunc) {
sm.method(http.MethodHead, path, handler)
}
func (sm *ServeMux) Options(path string, handler http.HandlerFunc) {
sm.method(http.MethodOptions, path, handler)
}
func (sm *ServeMux) Patch(path string, handler http.HandlerFunc) {
sm.method(http.MethodPatch, path, handler)
}
func (sm *ServeMux) method(method string, path string, handler http.HandlerFunc) {
sm.tree.insert(
method,
path,
Route{
Method: method,
Pattern: path,
HandlerFunc: handler,
},
)
}
type GracefulOpts struct {
TimeoutDuration time.Duration
}
// graceful shutdown
func ListenAndServeWithGracefulShutdown(srv *http.Server, opt GracefulOpts) error {
ctx, stop := signal.NotifyContext(context.Background(),
syscall.SIGTERM, os.Interrupt, os.Kill,
)
defer stop()
ctx, cancelCauseFunc := context.WithCancelCause(ctx)
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
cancelCauseFunc(err)
}
}()
<-ctx.Done() // wait signal
// check error caused by cancel or not
if err := context.Cause(ctx); err != nil {
if !errors.Is(err, context.Canceled) {
return err
}
}
// shutdown
ctx, cancelFunc := context.WithTimeout(context.Background(), opt.TimeoutDuration)
defer cancelFunc()
// shutdown server with timeout
var shutdownErr error = nil
if err := srv.Shutdown(ctx); err != nil {
shutdownErr = err
}
// check timeout occurred or not
if err := context.Cause(ctx); err != nil || shutdownErr != nil {
if errors.Is(err, context.DeadlineExceeded) {
return errors.Join(err, shutdownErr)
}
return shutdownErr
}
return nil
}