-
Notifications
You must be signed in to change notification settings - Fork 11
/
router.go
547 lines (489 loc) · 10.1 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
package echo
import (
"bytes"
)
var defaultRoute = &Route{}
type (
Router struct {
tree *node
static map[string]*methodHandler
routes []*Route
nroute map[string][]int
echo *Echo
}
meta struct {
name string
meta H
}
Route struct {
Method string
Path string
Handler Handler `json:"-" xml:"-"`
HandlerName string
Format string
Params []string //param names
Prefix string
Meta H
handler interface{} //原始handler
middleware []interface{} //中间件
}
endpoint struct {
handler Handler
rid int //routes index
}
node struct {
kind kind
label byte
prefix string
parent *node
children children
ppath string
pnames []string
methodHandler *methodHandler
}
kind uint8
children []*node
methodHandler struct {
connect *endpoint
delete *endpoint
get *endpoint
head *endpoint
options *endpoint
patch *endpoint
post *endpoint
put *endpoint
trace *endpoint
}
)
const (
skind kind = iota
pkind
akind
)
func (r *Route) IsZero() bool {
return r.Handler == nil
}
func (r *Route) apply(e *Echo) *Route {
handler := e.ValidHandler(r.handler)
middleware := r.middleware
if hn, ok := handler.(Name); ok {
r.HandlerName = hn.Name()
} else {
r.HandlerName = HandlerName(handler)
}
if mt, ok := handler.(Meta); ok {
r.Meta = mt.Meta()
} else {
r.Meta = H{}
}
for i := len(middleware) - 1; i >= 0; i-- {
m := middleware[i]
mw := e.ValidMiddleware(m)
handler = mw.Handle(handler)
}
r.Handler = handler
return r
}
func (m *methodHandler) addHandler(method string, h Handler, rid int) {
endpoint := &endpoint{handler: h, rid: rid}
switch method {
case GET:
m.get = endpoint
case POST:
m.post = endpoint
case PUT:
m.put = endpoint
case DELETE:
m.delete = endpoint
case PATCH:
m.patch = endpoint
case OPTIONS:
m.options = endpoint
case HEAD:
m.head = endpoint
case CONNECT:
m.connect = endpoint
case TRACE:
m.trace = endpoint
}
}
func (m *methodHandler) findHandler(method string) Handler {
endpoint := m.find(method)
if endpoint == nil {
return nil
}
return endpoint.handler
}
func (m *methodHandler) find(method string) *endpoint {
switch method {
case GET:
return m.get
case POST:
return m.post
case PUT:
return m.put
case DELETE:
return m.delete
case PATCH:
return m.patch
case OPTIONS:
return m.options
case HEAD:
return m.head
case CONNECT:
return m.connect
case TRACE:
return m.trace
default:
return nil
}
}
func (m *methodHandler) check405() HandlerFunc {
for _, method := range methods {
if r := m.findHandler(method); r != nil {
return MethodNotAllowedHandler
}
}
return NotFoundHandler
}
func (m *methodHandler) applyHandler(method string, ctx *xContext) {
endpoint := m.find(method)
if endpoint != nil {
ctx.handler = endpoint.handler
ctx.rid = endpoint.rid
} else {
ctx.handler = nil
}
}
func NewRouter(e *Echo) *Router {
return &Router{
tree: &node{
methodHandler: new(methodHandler),
},
static: map[string]*methodHandler{},
routes: []*Route{},
nroute: map[string][]int{},
echo: e,
}
}
func (r *Router) Handle(h Handler) Handler {
return HandlerFunc(func(c Context) error {
method := c.Request().Method()
path := c.Request().URL().Path()
r.Find(method, path, c)
return c.Handle(c)
})
}
// Add 添加路由
// method: 方法(GET/POST/PUT/DELETE/PATCH/OPTIONS/HEAD/CONNECT/TRACE)
// prefix: group前缀
// path: 路径(含前缀)
// h: Handler
// name: Handler名
// meta: meta数据
func (r *Router) Add(rt *Route, rid int) {
path := rt.Path
ppath := path // Pristine path
pnames := []string{} // Param names
uri := new(bytes.Buffer)
defer func() {
rt.Format = uri.String()
rt.Params = pnames
}()
for i, l := 0, len(path); i < l; i++ {
if path[i] == ':' {
uri.WriteString(`%v`)
j := i + 1
r.insert(rt.Method, path[:i], nil, skind, "", nil, -1)
for ; i < l && path[i] != '/'; i++ {
}
pnames = append(pnames, path[j:i])
path = path[:j] + path[i:]
i, l = j, len(path)
if i == l {
r.insert(rt.Method, path[:i], rt.Handler, pkind, ppath, pnames, rid)
return
}
r.insert(rt.Method, path[:i], nil, pkind, ppath, pnames, -1)
} else if path[i] == '*' {
uri.WriteString(`%v`)
r.insert(rt.Method, path[:i], nil, skind, "", nil, -1)
pnames = append(pnames, "*")
r.insert(rt.Method, path[:i+1], rt.Handler, akind, ppath, pnames, rid)
return
}
if i < l {
uri.WriteByte(path[i])
}
}
//static route
if m, ok := r.static[path]; ok {
m.addHandler(rt.Method, rt.Handler, rid)
} else {
m = &methodHandler{}
m.addHandler(rt.Method, rt.Handler, rid)
r.static[path] = m
}
//r.insert(method, path, h, skind, ppath, pnames, e)
return
}
func (r *Router) insert(method, path string, h Handler, t kind, ppath string, pnames []string, rid int) {
e := r.echo
// Adjust max param
l := len(pnames)
if *e.maxParam < l {
*e.maxParam = l
}
cn := r.tree // Current node as root
if cn == nil {
panic("echo => invalid method")
}
search := path
for {
sl := len(search)
pl := len(cn.prefix)
l := 0
// LCP
max := pl
if sl < max {
max = sl
}
for ; l < max && search[l] == cn.prefix[l]; l++ {
}
if l == 0 {
// At root node
cn.label = search[0]
cn.prefix = search
if h != nil {
cn.kind = t
cn.addHandler(method, h, rid)
cn.ppath = ppath
cn.pnames = pnames
}
} else if l < pl {
// Split node
n := newNode(cn.kind, cn.prefix[l:], cn, cn.children, cn.methodHandler, cn.ppath, cn.pnames)
// Reset parent node
cn.kind = skind
cn.label = cn.prefix[0]
cn.prefix = cn.prefix[:l]
cn.children = nil
cn.methodHandler = new(methodHandler)
cn.ppath = ""
cn.pnames = nil
cn.addChild(n)
if l == sl {
// At parent node
cn.kind = t
cn.addHandler(method, h, rid)
cn.ppath = ppath
cn.pnames = pnames
} else {
// Create child node
n = newNode(t, search[l:], cn, nil, new(methodHandler), ppath, pnames)
n.addHandler(method, h, rid)
cn.addChild(n)
}
} else if l < sl {
search = search[l:]
c := cn.findChildWithLabel(search[0])
if c != nil {
// Go deeper
cn = c
continue
}
// Create child node
n := newNode(t, search, cn, nil, new(methodHandler), ppath, pnames)
n.addHandler(method, h, rid)
cn.addChild(n)
} else {
// Node already exists
if h != nil {
cn.addHandler(method, h, rid)
cn.ppath = ppath
cn.pnames = pnames
}
}
return
}
}
func newNode(t kind, pre string, p *node, c children, mh *methodHandler, ppath string, pnames []string) *node {
return &node{
kind: t,
label: pre[0],
prefix: pre,
parent: p,
children: c,
ppath: ppath,
pnames: pnames,
methodHandler: mh,
}
}
func (n *node) addChild(c *node) {
n.children = append(n.children, c)
}
func (n *node) findChild(l byte, t kind) *node {
for _, c := range n.children {
if c.label == l && c.kind == t {
return c
}
}
return nil
}
func (n *node) findChildWithLabel(l byte) *node {
for _, c := range n.children {
if c.label == l {
return c
}
}
return nil
}
func (n *node) findChildByKind(t kind) *node {
for _, c := range n.children {
if c.kind == t {
return c
}
}
return nil
}
func (n *node) addHandler(method string, h Handler, rid int) {
n.methodHandler.addHandler(method, h, rid)
}
func (n *node) findHandler(method string) Handler {
return n.methodHandler.findHandler(method)
}
func (n *node) find(method string) *endpoint {
return n.methodHandler.find(method)
}
func (n *node) check405() HandlerFunc {
return n.methodHandler.check405()
}
func (n *node) applyHandler(method string, ctx *xContext) {
n.methodHandler.applyHandler(method, ctx)
ctx.path = n.ppath
ctx.pnames = n.pnames
}
func (r *Router) Find(method, path string, context Context) {
ctx := context.Object()
ctx.path = path
cn := r.tree // Current node as root
if m, ok := r.static[path]; ok {
m.applyHandler(method, ctx)
if ctx.handler == nil {
ctx.handler = m.check405()
}
return
}
var (
search = path
c *node // Child node
n int // Param counter
nk kind // Next kind
nn *node // Next node
ns string // Next search
pvalues = context.ParamValues()
)
// Search order static > param > any
for {
if search == "" {
goto End
}
pl := 0 // Prefix length
l := 0 // LCP length
if cn.label != ':' {
sl := len(search)
pl = len(cn.prefix)
// LCP
max := pl
if sl < max {
max = sl
}
for ; l < max && search[l] == cn.prefix[l]; l++ {
}
}
if l == pl {
// Continue search
search = search[l:]
} else {
cn = nn
search = ns
if nk == pkind {
goto Param
} else if nk == akind {
goto Any
}
// Not found
return
}
if search == "" {
goto End
}
// Static node
if c = cn.findChild(search[0], skind); c != nil {
// Save next
if cn.prefix[len(cn.prefix)-1] == '/' {
nk = pkind
nn = cn
ns = search
}
cn = c
continue
}
// Param node
Param:
if c = cn.findChildByKind(pkind); c != nil {
if len(pvalues) == n {
continue
}
// Save next
if cn.prefix[len(cn.prefix)-1] == '/' {
nk = akind
nn = cn
ns = search
}
cn = c
i, l := 0, len(search)
for ; i < l && search[i] != '/'; i++ {
}
pvalues[n] = search[:i]
n++
search = search[i:]
continue
}
// Any node
Any:
if cn = cn.findChildByKind(akind); cn == nil {
if nn != nil {
cn = nn
nn = nil // Next
search = ns
if nk == pkind {
goto Param
} else if nk == akind {
goto Any
}
}
// Not found
return
}
pvalues[len(cn.pnames)-1] = search
goto End
}
End:
cn.applyHandler(method, ctx)
// NOTE: Slow zone...
if ctx.handler == nil {
// Dig further for any, might have an empty value for *, e.g.
// serving a directory. Issue #207.
if child := cn.findChildByKind(akind); child != nil {
child.applyHandler(method, ctx)
if ctx.handler == nil {
ctx.handler = child.check405()
}
pvalues[len(child.pnames)-1] = ""
return
}
ctx.handler = cn.check405()
}
return
}