-
Notifications
You must be signed in to change notification settings - Fork 37
/
router.go
527 lines (444 loc) · 9.91 KB
/
router.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package air
import (
ppath "path"
"strings"
"sync"
)
// router is a registry of all registered routes.
type router struct {
sync.Mutex
a *Air
routeTree *routeNode
registeredRoutes map[string]bool
maxRouteParams int
routeParamValuesPool sync.Pool
}
// newRouter returns a new instance of the `router` with the a.
func newRouter(a *Air) *router {
r := &router{
a: a,
routeTree: &routeNode{
handlers: map[string]Handler{},
},
registeredRoutes: map[string]bool{},
}
r.routeParamValuesPool.New = func() interface{} {
return make([]string, r.maxRouteParams)
}
return r
}
// register registers a new route for the method and path with the matching h in
// the r with the optional route-level gases.
func (r *router) register(method, path string, h Handler, gases ...Gas) {
r.Lock()
defer r.Unlock()
if path == "" {
panic("air: route path cannot be empty")
} else if h == nil {
panic("air: route handler cannot be nil")
}
hasTrailingSlash := path[len(path)-1] == '/'
path = ppath.Clean(path)
if hasTrailingSlash && path != "/" {
path += "/"
}
if path[0] != '/' {
panic("air: route path must start with /")
} else if strings.Count(path, ":") > 1 {
ps := strings.Split(path, "/")
for _, p := range ps {
if strings.Count(p, ":") > 1 {
panic("air: adjacent param names in route " +
"path must be separated by /")
}
}
} else if strings.Contains(path, "*") {
if strings.Count(path, "*") > 1 {
panic("air: only one * is allowed in route path")
} else if path[len(path)-1] != '*' {
panic("air: * can only appear at end of route path")
} else if strings.Contains(
path[strings.LastIndex(path, "/"):],
":",
) {
panic("air: adjacent param name and * in route path " +
"must be separated by /")
}
}
routeName := method + path
for i, l := len(method), len(routeName); i < l; i++ {
if routeName[i] == ':' {
j := i + 1
for ; i < l && routeName[i] != '/'; i++ {
}
routeName = routeName[:j] + routeName[i:]
i, l = j, len(routeName)
if i == l {
break
}
}
}
if r.registeredRoutes[routeName] {
panic("air: route already exists")
} else {
r.registeredRoutes[routeName] = true
}
rh := func(req *Request, res *Response) error {
h := h
for i := len(gases) - 1; i >= 0; i-- {
h = gases[i](h)
}
return h(req, res)
}
paramNames := []string{}
for i, l := 0, len(path); i < l; i++ {
if path[i] == ':' {
j := i + 1
r.insert(
method,
path[:i],
nil,
routeNodeTypeSTATIC,
nil,
)
for ; i < l && path[i] != '/'; i++ {
}
paramName := path[j:i]
for _, pn := range paramNames {
if pn == paramName {
panic("air: route path cannot have " +
"duplicate param names")
}
}
paramNames = append(paramNames, paramName)
path = path[:j] + path[i:]
if i, l = j, len(path); i == l {
r.insert(
method,
path,
rh,
routeNodeTypePARAM,
paramNames,
)
return
}
r.insert(
method,
path[:i],
nil,
routeNodeTypePARAM,
paramNames,
)
} else if path[i] == '*' {
r.insert(
method,
path[:i],
nil,
routeNodeTypeSTATIC,
nil,
)
paramNames = append(paramNames, "*")
r.insert(
method,
path[:i+1],
rh,
routeNodeTypeANY,
paramNames,
)
return
}
}
r.insert(method, path, rh, routeNodeTypeSTATIC, paramNames)
}
// insert inserts a new route into the `r.routeTree`.
func (r *router) insert(
method string,
path string,
h Handler,
nt routeNodeType,
paramNames []string,
) {
if l := len(paramNames); l > r.maxRouteParams {
r.maxRouteParams = l
}
var (
s = path // Search
cn = r.routeTree // Current node
nn *routeNode // Next node
sl int // Search length
pl int // Prefix length
ll int // LCP length
ml int // Minimum length of sl and pl
)
for {
sl = len(s)
pl = len(cn.prefix)
ll = 0
ml = pl
if sl < ml {
ml = sl
}
for ; ll < ml && s[ll] == cn.prefix[ll]; ll++ {
}
if ll == 0 { // At root node
cn.label = s[0]
cn.nType = nt
cn.prefix = s
cn.paramNames = paramNames
if h != nil {
cn.handlers[method] = h
}
} else if ll < pl { // Split node
nn = &routeNode{
label: cn.prefix[ll],
nType: cn.nType,
prefix: cn.prefix[ll:],
children: cn.children,
paramNames: cn.paramNames,
handlers: cn.handlers,
}
// Reset current node.
cn.label = cn.prefix[0]
cn.nType = routeNodeTypeSTATIC
cn.prefix = cn.prefix[:ll]
cn.children = []*routeNode{nn}
cn.paramNames = nil
cn.handlers = map[string]Handler{}
if ll == sl { // At current node
cn.nType = nt
cn.paramNames = paramNames
if h != nil {
cn.handlers[method] = h
}
} else { // Create child node
nn = &routeNode{
label: s[ll],
nType: nt,
prefix: s[ll:],
paramNames: paramNames,
handlers: map[string]Handler{},
}
if h != nil {
nn.handlers[method] = h
}
cn.children = append(cn.children, nn)
}
} else if ll < sl {
s = s[ll:]
if nn = cn.childByLabel(s[0]); nn != nil {
// Go deeper.
cn = nn
continue
}
// Create child node.
nn = &routeNode{
label: s[0],
nType: nt,
prefix: s,
handlers: map[string]Handler{},
paramNames: paramNames,
}
if h != nil {
nn.handlers[method] = h
}
cn.children = append(cn.children, nn)
} else { // Node already exists
if len(cn.paramNames) == 0 {
cn.paramNames = paramNames
}
if h != nil {
cn.handlers[method] = h
}
}
break
}
}
// route returns a handler registered for the req.
func (r *router) route(req *Request) Handler {
var (
s = req.RawPath() // Search
cn = r.routeTree // Current node
nn *routeNode // Next node
sn *routeNode // Saved node
snt routeNodeType // Saved type
ss string // Saved search
sapn *routeNode // Saved ANY parent node
saps string // Saved ANY parent search
sl int // Search length
pl int // Prefix length
ll int // LCP length
ml int // Minimum length of sl and pl
i int // Index
pc int // Param counter
)
// Search order: STATIC > PARAM > ANY.
for {
if s == "" {
if len(cn.handlers) == 0 {
if cn.childByType(routeNodeTypePARAM) != nil {
goto TryPARAM
}
if cn.childByType(routeNodeTypeANY) != nil {
goto TryANY
}
if sapn != nil {
goto Struggle
}
}
break
}
if s[0] == '/' { // Skip continuous "/"
for i, sl = 1, len(s); i < sl && s[i] == '/'; i++ {
}
s = s[i-1:]
}
pl = 0
ll = 0
if cn.label != ':' {
pl = len(cn.prefix)
ml = pl
if sl = len(s); sl < ml {
ml = sl
}
for ; ll < ml && s[ll] == cn.prefix[ll]; ll++ {
}
}
if ll != pl {
goto Struggle
}
if s = s[ll:]; s == "" {
continue
}
// Save ANY parent node for struggling.
if cn != sapn && cn.childByType(routeNodeTypeANY) != nil {
sapn = cn
saps = s
}
// Try STATIC node.
if nn = cn.child(s[0], routeNodeTypeSTATIC); nn != nil {
// Save node for struggling.
if pl = len(cn.prefix); pl > 0 &&
cn.prefix[pl-1] == '/' {
sn = cn
snt = routeNodeTypePARAM
ss = s
}
cn = nn
continue
}
// Try PARAM node.
TryPARAM:
if nn = cn.childByType(routeNodeTypePARAM); nn != nil {
// Save node for struggling.
if pl = len(cn.prefix); pl > 0 &&
cn.prefix[pl-1] == '/' {
sn = cn
snt = routeNodeTypeANY
ss = s
}
cn = nn
for i, sl = 0, len(s); i < sl && s[i] != '/'; i++ {
}
if req.routeParamValues == nil {
req.routeParamValues = r.allocRouteParamValues()
}
if pc < len(cn.paramNames) {
pc++
}
req.routeParamValues[pc-1] = s[:i]
s = s[i:]
continue
}
// Try ANY node.
TryANY:
if cn = cn.childByType(routeNodeTypeANY); cn != nil {
if req.routeParamValues == nil {
req.routeParamValues = r.allocRouteParamValues()
}
pc = len(cn.paramNames)
req.routeParamValues[pc-1] = s
break
}
// Struggle for the former node.
Struggle:
if sn != nil {
cn = sn
sn = nil
s = ss
switch snt {
case routeNodeTypePARAM:
goto TryPARAM
case routeNodeTypeANY:
goto TryANY
}
} else if sapn != nil {
cn = sapn
sapn = nil
s = saps
goto TryANY
}
return r.a.NotFoundHandler
}
h := cn.handlers[req.Method]
if h != nil {
req.routeParamNames = cn.paramNames
} else if len(cn.handlers) > 0 {
h = r.a.MethodNotAllowedHandler
} else {
h = r.a.NotFoundHandler
}
return h
}
// allocRouteParamValues reuses or creates a string slice for storing route
// param values.
func (r *router) allocRouteParamValues() []string {
rpvs := r.routeParamValuesPool.Get().([]string)
if len(rpvs) < r.maxRouteParams {
rpvs = r.routeParamValuesPool.New().([]string)
}
return rpvs
}
// routeNode is the node of the route radix tree.
type routeNode struct {
label byte
nType routeNodeType
prefix string
children []*routeNode
paramNames []string
handlers map[string]Handler
}
// child returns a child node of the rn by the l and t.
func (rn *routeNode) child(l byte, t routeNodeType) *routeNode {
for _, c := range rn.children {
if c.label == l && c.nType == t {
return c
}
}
return nil
}
// childByLabel returns a child node of the rn by the l.
func (rn *routeNode) childByLabel(l byte) *routeNode {
for _, c := range rn.children {
if c.label == l {
return c
}
}
return nil
}
// childByType returns a child node of the rn by the t.
func (rn *routeNode) childByType(t routeNodeType) *routeNode {
for _, c := range rn.children {
if c.nType == t {
return c
}
}
return nil
}
// routeNodeType is the type of the `routeNode`.
type routeNodeType uint8
// The route node types.
const (
routeNodeTypeSTATIC routeNodeType = iota
routeNodeTypePARAM
routeNodeTypeANY
)