-
Notifications
You must be signed in to change notification settings - Fork 11
/
router.go
1147 lines (1050 loc) · 26.6 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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package echo
import (
"bytes"
"fmt"
"net/url"
"regexp"
"sort"
"strings"
"github.com/webx-top/echo/param"
)
var (
defaultRoute = &Route{}
emptyMeta = H{}
)
type (
Router struct {
tree *node
static map[string]*methodHandler
routes []*Route
nroute map[string][]int
echo *Echo
}
Rewriter interface {
Rewrite(string) string
}
Route struct {
Host string
Method string
Path string
Handler Handler `json:"-" xml:"-"`
Name string
Format string
Params []string //param names
Prefix string
Meta H
handler interface{} //原始handler
middleware []interface{} //中间件
}
Routes []*Route
endpoint struct {
handler Handler
rid int //routes index
}
node struct {
kind kind
label byte
prefix string
parent *node
staticChildren children
ppath string
pnames []string
methodHandler *methodHandler
regExp *regexp.Regexp
regexChild *node
paramChild *node
anyChild *node
// isLeaf indicates that node does not have child routes
isLeaf bool
// isHandler indicates that node has at least one handler registered to it
isHandler bool
}
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 (
staticKind kind = iota // static kind
regexKind // regexp kind
paramKind // param kind
anyKind // any kind
regexLabel = byte('<')
paramLabel = byte(':')
anyLabel = byte('*')
)
func (r Routes) SetName(name string) IRouter {
for _, route := range r {
route.SetName(name)
}
return r
}
func (r Routes) SetMeta(meta H) IRouter {
for _, route := range r {
route.SetMeta(meta)
}
return r
}
func (r Routes) SetMetaKV(key string, value interface{}) IRouter {
for _, route := range r {
route.SetMetaKV(key, value)
}
return r
}
func (r Routes) GetName() string {
for _, route := range r {
return route.GetName()
}
return ``
}
func (r Routes) GetMeta() H {
for _, route := range r {
return route.Meta
}
return nil
}
func (r *Route) SetName(name string) IRouter {
r.Name = name
return r
}
func (r *Route) SetMeta(meta H) IRouter {
r.Meta = meta
return r
}
func (r *Route) SetMetaKV(key string, value interface{}) IRouter {
if r.Meta == nil {
r.Meta = H{}
}
r.Meta[key] = value
return r
}
func (r *Route) GetName() string {
return r.Name
}
func (r *Route) GetMeta() H {
return r.Meta
}
func (r *Route) IsZero() bool {
return r.Handler == nil
}
func (r *Route) Bool(name string, defaults ...interface{}) bool {
if r.Meta == nil {
return false
}
return r.Meta.Bool(name, defaults...)
}
func (r *Route) String(name string, defaults ...interface{}) string {
if r.Meta == nil {
return ``
}
return r.Meta.String(name, defaults...)
}
func (r *Route) Float64(name string, defaults ...interface{}) float64 {
if r.Meta == nil {
return 0
}
return r.Meta.Float64(name, defaults...)
}
func (r *Route) Float32(name string, defaults ...interface{}) float32 {
if r.Meta == nil {
return 0
}
return r.Meta.Float32(name, defaults...)
}
func (r *Route) Uint64(name string, defaults ...interface{}) uint64 {
if r.Meta == nil {
return 0
}
return r.Meta.Uint64(name, defaults...)
}
func (r *Route) Uint32(name string, defaults ...interface{}) uint32 {
if r.Meta == nil {
return 0
}
return r.Meta.Uint32(name, defaults...)
}
func (r *Route) Uint(name string, defaults ...interface{}) uint {
if r.Meta == nil {
return 0
}
return r.Meta.Uint(name, defaults...)
}
func (r *Route) Int64(name string, defaults ...interface{}) int64 {
if r.Meta == nil {
return 0
}
return r.Meta.Int64(name, defaults...)
}
func (r *Route) Int32(name string, defaults ...interface{}) int32 {
if r.Meta == nil {
return 0
}
return r.Meta.Int32(name, defaults...)
}
func (r *Route) Int(name string, defaults ...interface{}) int {
if r.Meta == nil {
return 0
}
return r.Meta.Int(name, defaults...)
}
func (r *Route) Get(name string, defaults ...interface{}) interface{} {
if r.Meta == nil {
return nil
}
return r.Meta.Get(name, defaults...)
}
func (r *Route) GetStore(names ...string) H {
if r.Meta == nil {
return emptyMeta
}
res := r.Meta
for _, name := range names {
res = res.GetStore(name)
}
return res
}
func (r *Route) MakeURI(e *Echo, params ...interface{}) (uri string) {
length := len(params)
if length != 1 {
uri = fmt.Sprintf(r.Format, params...)
uri = e.wrapURI(uri)
return
}
switch val := params[0].(type) {
case url.Values:
uri = r.Path
if len(r.Params) > 0 {
values := make([]interface{}, len(r.Params))
for index, name := range r.Params {
values[index] = val.Get(name)
val.Del(name)
}
uri = fmt.Sprintf(r.Format, values...)
}
uri = e.wrapURI(uri)
q := val.Encode()
if len(q) > 0 {
uri += `?` + q
}
case H:
uri = r.Path
if len(r.Params) > 0 {
values := make([]interface{}, len(r.Params))
for index, name := range r.Params {
var ok bool
values[index], ok = val[name]
if ok {
delete(val, name)
}
}
uri = fmt.Sprintf(r.Format, values...)
}
uri = e.wrapURI(uri)
sep := `?`
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
uri += sep + url.QueryEscape(k) + `=` + url.QueryEscape(val.String(k))
sep = `&`
}
case map[string]interface{}:
uri = r.Path
if len(r.Params) > 0 {
values := make([]interface{}, len(r.Params))
for index, name := range r.Params {
var ok bool
values[index], ok = val[name]
if ok {
delete(val, name)
}
}
uri = fmt.Sprintf(r.Format, values...)
}
uri = e.wrapURI(uri)
sep := `?`
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
uri += sep + url.QueryEscape(k) + `=` + url.QueryEscape(param.AsString(val[k]))
sep = `&`
}
case map[string]string:
uri = r.Path
if len(r.Params) > 0 {
values := make([]interface{}, len(r.Params))
for index, name := range r.Params {
var ok bool
values[index], ok = val[name]
if ok {
delete(val, name)
}
}
uri = fmt.Sprintf(r.Format, values...)
}
uri = e.wrapURI(uri)
sep := `?`
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
uri += sep + url.QueryEscape(k) + `=` + url.QueryEscape(val[k])
sep = `&`
}
case []interface{}:
uri = fmt.Sprintf(r.Format, val...)
uri = e.wrapURI(uri)
default:
uri = fmt.Sprintf(r.Format, val)
uri = e.wrapURI(uri)
}
return
}
func (r *Route) apply(e *Echo) *Route {
handler := e.ValidHandler(r.handler)
middleware := r.middleware
if len(r.Name) == 0 {
if hn, ok := handler.(Name); ok {
r.Name = hn.Name()
}
if len(r.Name) == 0 {
r.Name = HandlerName(handler)
}
}
if r.Meta == nil {
r.Meta = H{}
}
if mt, ok := handler.(Meta); ok {
meta := mt.Meta()
if len(r.Meta) == 0 {
r.Meta = meta
} else {
r.Meta.DeepMerge(meta)
}
}
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 (e *endpoint) Map() H {
return H{`handler`: HandlerName(e.handler), `index`: e.rid}
}
func (m *methodHandler) isHandler() bool {
return m.connect != nil ||
m.delete != nil ||
m.get != nil ||
m.head != nil ||
m.options != nil ||
m.patch != nil ||
m.post != nil ||
m.put != nil ||
m.trace != nil
}
func (m *methodHandler) Map() H {
r := H{}
if m.get != nil {
r[`get`] = m.get.Map()
}
if m.post != nil {
r[`post`] = m.post.Map()
}
if m.put != nil {
r[`put`] = m.put.Map()
}
if m.delete != nil {
r[`delete`] = m.delete.Map()
}
if m.patch != nil {
r[`patch`] = m.patch.Map()
}
if m.options != nil {
r[`options`] = m.options.Map()
}
if m.head != nil {
r[`head`] = m.head.Map()
}
if m.connect != nil {
r[`connect`] = m.connect.Map()
}
if m.trace != nil {
r[`trace`] = m.trace.Map()
}
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) checkMethodNotAllowed() 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(c Context) Handler {
return r.Dispatch(c, c.Request().URL().Path())
}
func (r *Router) Dispatch(c Context, path string, _method ...string) Handler {
method := c.Request().Method()
if len(_method) > 0 && len(_method[0]) > 0 {
method = _method[0]
}
found := r.Find(method, path, c)
if !found {
ext := c.DefaultExtension()
if len(ext) == 0 {
return c
}
if strings.HasSuffix(path, ext) {
path = strings.TrimSuffix(path, ext)
r.Find(method, path, c)
}
}
return 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
//Dump(rt)
}()
for i, l := 0, len(path); i < l; i++ {
if path[i] == paramLabel {
if i > 0 && path[i-1] == '\\' {
continue
}
uri.WriteString(`%v`)
j := i + 1
r.insert(rt.Method, path[:i], nil, staticKind, "", nil, -1)
for ; i < l && path[i] != '/'; i++ {
}
pname := path[j:i]
pnames = append(pnames, pname)
path = path[:j] + path[i:]
i, l = j, len(path)
if i == l {
// path node is last fragment of route path. ie. `/users/:id`
r.insert(rt.Method, path[:i], rt.Handler, paramKind, ppath, pnames, rid)
} else {
r.insert(rt.Method, path[:i], nil, paramKind, "", nil, -1)
}
} else if path[i] == regexLabel {
if i > 0 && path[i-1] == '\\' {
continue
}
uri.WriteString(`%v`)
j := i + 1
r.insert(rt.Method, path[:i], nil, staticKind, "", nil, -1)
for ; i < l && path[i] != '>'; i++ {
}
pname := path[j:i]
parts := strings.SplitN(pname, `:`, 2)
var regExpr string
if len(parts) == 2 {
pname = parts[0]
regExpr = `(` + parts[1] + `)`
} else {
regExpr = `([^/]+)`
}
pnames = append(pnames, pname)
if path[i] == '>' {
i++
}
if len(path) > i {
path = path[:j] + path[i:]
} else {
path = path[:j]
}
i, l = j, len(path)
r.insert(rt.Method, path[:i], rt.Handler, regexKind, ppath, pnames, rid, regExpr)
} else if path[i] == '*' {
uri.WriteString(`%v`)
r.insert(rt.Method, path[:i], nil, staticKind, "", nil, -1)
pnames = append(pnames, "*")
r.insert(rt.Method, path[:i+1], rt.Handler, anyKind, ppath, pnames, rid)
continue
}
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(rt.Method, path, rt.Handler, staticKind, ppath, pnames, rid)
}
func (r *Router) insert(method, path string, h Handler, t kind, ppath string, pnames []string, rid int, regExpr ...string) {
e := r.echo
// Adjust max param
paramLen := len(pnames)
if *e.maxParam < paramLen {
*e.maxParam = paramLen
}
currentNode := r.tree // Current node as root
if currentNode == nil {
panic("echo: invalid method")
}
search := path
for {
searchLen := len(search)
prefixLen := len(currentNode.prefix)
lcpLen := 0
// LCP
max := prefixLen
if searchLen < max {
max = searchLen
}
for ; lcpLen < max && search[lcpLen] == currentNode.prefix[lcpLen]; lcpLen++ {
}
if lcpLen == 0 {
// At root node
if len(search) > 0 {
currentNode.label = search[0]
}
currentNode.prefix = search
if h != nil {
currentNode.kind = t
currentNode.addHandler(method, h, rid)
currentNode.ppath = ppath
currentNode.pnames = pnames
}
currentNode.isLeaf = currentNode.IsLeaf()
} else if lcpLen < prefixLen {
// Split node
n := newNode(
currentNode.kind,
currentNode.prefix[lcpLen:],
currentNode,
currentNode.staticChildren,
currentNode.methodHandler,
currentNode.ppath,
currentNode.pnames,
currentNode.regexChild,
currentNode.paramChild,
currentNode.anyChild,
regExpr...,
)
// Update parent path for all children to new node
for _, child := range currentNode.staticChildren {
child.parent = n
}
if currentNode.paramChild != nil {
currentNode.paramChild.parent = n
}
if currentNode.anyChild != nil {
currentNode.anyChild.parent = n
}
// Reset parent node
currentNode.kind = staticKind
currentNode.label = currentNode.prefix[0]
currentNode.prefix = currentNode.prefix[:lcpLen]
currentNode.staticChildren = nil
currentNode.methodHandler = new(methodHandler)
currentNode.ppath = ""
currentNode.pnames = nil
currentNode.regExp = nil
currentNode.paramChild = nil
currentNode.anyChild = nil
currentNode.isLeaf = false
currentNode.isHandler = false
currentNode.addStaticChild(n)
if lcpLen == searchLen {
// At parent node
currentNode.kind = t
currentNode.addHandler(method, h, rid)
currentNode.ppath = ppath
currentNode.pnames = pnames
} else {
// Create child node
n = newNode(t, search[lcpLen:], currentNode, nil, new(methodHandler), ppath, pnames, nil, nil, nil, regExpr...)
n.addHandler(method, h, rid)
// Only Static children could reach here
currentNode.addStaticChild(n)
}
currentNode.isLeaf = currentNode.IsLeaf()
} else if lcpLen < searchLen {
search = search[lcpLen:]
c := currentNode.findChildWithLabel(search[0])
if c != nil {
// Go deeper
currentNode = c
continue
}
// Create child node
n := newNode(t, search, currentNode, nil, new(methodHandler), ppath, pnames, nil, nil, nil, regExpr...)
n.addHandler(method, h, rid)
switch t {
case staticKind:
currentNode.addStaticChild(n)
case regexKind:
currentNode.regexChild = n
case paramKind:
currentNode.paramChild = n
case anyKind:
currentNode.anyChild = n
}
currentNode.isLeaf = currentNode.IsLeaf()
} else {
// Node already exists
if h != nil {
currentNode.addHandler(method, h, rid)
currentNode.ppath = ppath
if len(currentNode.pnames) == 0 {
currentNode.pnames = pnames
}
}
}
return
}
}
func newNode(t kind, pre string, p *node, sc children, mh *methodHandler, ppath string, pnames []string, regexChildren, paramChildren, anyChildren *node, regExpr ...string) *node {
n := &node{
kind: t,
label: pre[0],
prefix: pre,
parent: p,
staticChildren: sc,
ppath: ppath,
pnames: pnames,
methodHandler: mh,
regexChild: regexChildren,
paramChild: paramChildren,
anyChild: anyChildren,
isHandler: mh.isHandler(),
}
n.isLeaf = n.IsLeaf()
if len(regExpr) > 0 && len(regExpr[0]) > 0 {
if n.isLeaf && strings.HasSuffix(n.ppath, `:`+regExpr[0]+`>`) { // <name:regExpr>
n.regExp = regexp.MustCompile(`^` + regExpr[0] + `$`)
} else {
n.regExp = regexp.MustCompile(`^` + regExpr[0])
}
}
return n
}
func (n *node) String() string {
return Dump(n.Tree(), false)
}
func (n *node) IsLeaf() bool {
return n.staticChildren == nil && n.regexChild == nil && n.paramChild == nil && n.anyChild == nil
}
func (n *node) Tree() H {
children := make([]H, len(n.staticChildren))
for k, v := range n.staticChildren {
children[k] = v.Tree()
}
var (
regExpr string
regexChild H
paramChild H
anyChild H
)
if n.regExp != nil {
regExpr = n.regExp.String()
}
if n.regexChild != nil {
regexChild = n.regexChild.Tree()
}
if n.paramChild != nil {
paramChild = n.paramChild.Tree()
}
if n.anyChild != nil {
anyChild = n.anyChild.Tree()
}
return H{
"kind": n.kind,
"label": string([]byte{n.label}),
"prefix": n.prefix,
"parent": n.parent,
"staticChildren": children,
"ppath": n.ppath,
"pnames": n.pnames,
"methodHandler": n.methodHandler.Map(),
"regExpr": regExpr,
"regexChild": regexChild,
"paramChild": paramChild,
"anyChild": anyChild,
"isLeaf": n.isLeaf,
"isHandler": n.isHandler,
}
}
func (n *node) addStaticChild(c *node) {
n.staticChildren = append(n.staticChildren, c)
}
func (n *node) findStaticChild(l byte) *node {
for _, c := range n.staticChildren {
if c.label == l {
return c
}
}
return nil
}
func (n *node) findChildWithLabel(l byte) *node {
for _, c := range n.staticChildren {
if c.label == l {
return c
}
}
if l == regexLabel {
return n.regexChild
}
if l == paramLabel {
return n.paramChild
}
if l == anyLabel {
return n.anyChild
}
return nil
}
func (n *node) findRegexChild(search string) (*node, []int) {
var matchIndex []int
c := n.regexChild
matchIndex = c.regExp.FindStringSubmatchIndex(search)
//fmt.Printf("%s => %s: %#v\n", search, c.regExp.String(), matchIndex)
if len(matchIndex) > 3 {
return c, matchIndex
}
return nil, matchIndex
}
func (n *node) addHandler(method string, h Handler, rid int) {
n.methodHandler.addHandler(method, h, rid)
if h != nil {
n.isHandler = true
} else {
n.isHandler = n.methodHandler.isHandler()
}
}
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) checkMethodNotAllowed() Handler {
return n.methodHandler.checkMethodNotAllowed()
}
func (n *node) applyHandler(method string, ctx *xContext) {
n.methodHandler.applyHandler(method, ctx)
ctx.path = n.ppath
ctx.pnames = n.pnames
}
func (r *Router) Tree() H {
return r.tree.Tree()
}
func (r *Router) String() string {
return r.tree.String()
}
func (r *Router) Find(method, path string, context Context) (found bool) {
ctx := context.Object()
ctx.path = path
currentNode := r.tree // Current node as root
if m, ok := r.static[path]; ok {
m.applyHandler(method, ctx)
if ctx.handler == nil {
ctx.handler = m.checkMethodNotAllowed()
return false
}
return true
}
var (
previousBestMatchNode *node
matchedEndpoint *endpoint
// search stores the remaining path to check for match. By each iteration we move from start of path to end of the path
// and search value gets shorter and shorter.
search = path
searchIndex = 0
paramIndex int // Param counter
paramValues = context.ParamValues()
matchIndex []int
)
// Backtracking is needed when a dead end (leaf node) is reached in the router tree.
// To backtrack the current node will be changed to the parent node and the next kind for the
// router logic will be returned based on fromKind or kind of the dead end node (static > param > any).
// For example if there is no static node match we should check parent next sibling by kind (param).
// Backtracking itself does not check if there is a next sibling, this is done by the router logic.
backtrackToNextNodeKind := func(fromKind kind) (nextNodeKind kind, valid bool) {
previous := currentNode
currentNode = previous.parent
valid = currentNode != nil
// Next node type by priority
if previous.kind == anyKind {
nextNodeKind = staticKind
} else {
nextNodeKind = previous.kind + 1
}
if fromKind == staticKind {
// when backtracking is done from static kind block we did not change search so nothing to restore
return
}
// restore search to value it was before we move to current node we are backtracking from.
if previous.kind == staticKind {
searchIndex -= len(previous.prefix)
} else {
paramIndex--
// for param/any node.prefix value is always `:` so we can not deduce searchIndex from that and must use pValue
// for that index as it would also contain part of path we cut off before moving into node we are backtracking from
searchIndex -= len(paramValues[paramIndex])
paramValues[paramIndex] = ""
}
search = path[searchIndex:]
return
}
// Router tree is implemented by longest common prefix array (LCP array) https://en.wikipedia.org/wiki/LCP_array
// Tree search is implemented as for loop where one loop iteration is divided into 3 separate blocks
// Each of these blocks checks specific kind of node (static/param/any). Order of blocks reflex their priority in routing.
// Search order/priority is: static > param > any.
//
// Note: backtracking in tree is implemented by replacing/switching currentNode to previous node
// and hoping to (goto statement) next block by priority to check if it is the match.
for {
prefixLen := 0 // Prefix length
lcpLen := 0 // LCP length
if currentNode.kind == staticKind {
searchLen := len(search)
prefixLen = len(currentNode.prefix)
// LCP - Longest Common Prefix (https://en.wikipedia.org/wiki/LCP_array)
max := prefixLen