-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathtree.go
442 lines (396 loc) · 9.44 KB
/
tree.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
package baa
import (
"fmt"
"sync"
)
// Tree provlider router for baa with radix tree
type Tree struct {
autoHead bool
autoTrailingSlash bool
mu sync.RWMutex
notFoundHandler HandlerFunc
groups []*group
nodes [RouteLength]*Leaf
namedNodes map[string]string
}
// Leaf is a tree node
type Leaf struct {
hasParam bool
alpha byte
pattern string
param string
root *Tree
parent *Leaf
children []*Leaf
handlers []HandlerFunc
}
// group route
type group struct {
pattern string
handlers []HandlerFunc
}
// newTree create a router instance
func newTree() Router {
t := new(Tree)
for i := 0; i < len(t.nodes); i++ {
t.nodes[i] = newLeaf("/", nil, nil)
}
t.namedNodes = make(map[string]string)
t.groups = make([]*group, 0)
return t
}
// newLeaf create a route node
func newLeaf(pattern string, handles []HandlerFunc, root *Tree) *Leaf {
l := new(Leaf)
l.pattern = pattern
l.alpha = pattern[0]
l.handlers = handles
l.root = root
l.children = make([]*Leaf, 0)
return l
}
// newGroup create a group router
func newGroup() *group {
g := new(group)
g.handlers = make([]HandlerFunc, 0)
return g
}
// SetAutoHead sets the value who determines whether add HEAD method automatically
// when GET method is added. Combo router will not be affected by this value.
func (t *Tree) SetAutoHead(v bool) {
t.autoHead = v
}
// SetAutoTrailingSlash optional trailing slash.
func (t *Tree) SetAutoTrailingSlash(v bool) {
t.autoTrailingSlash = v
}
// Match match the route
func (t *Tree) Match(method, pattern string, c *Context) RouteNode {
var i, l int
var root, nn *Leaf
root = t.nodes[RouterMethods[method]]
for {
// static route
if !root.hasParam {
l = len(root.pattern)
if l <= len(pattern) && root.pattern == pattern[:l] {
if l == len(pattern) {
return root
}
if len(root.children) == 0 {
return nil
}
pattern = pattern[l:]
} else {
return nil
}
} else {
// params route
l = len(pattern)
if len(root.children) == 0 {
i = l
} else {
for i = 0; i < l && pattern[i] != '/'; i++ {
}
}
c.SetParam(root.param, pattern[:i])
if i == l {
return root
}
pattern = pattern[i:]
}
// only one child
if len(root.children) == 1 {
if root.children[0].hasParam || root.children[0].alpha == pattern[0] {
root = root.children[0]
continue
}
break
}
// children static route
if nn = root.findChild(pattern[0]); nn != nil {
root = nn
continue
}
// children param route
if root.children[0].hasParam {
root = root.children[0]
continue
}
break
}
return nil
}
// URLFor use named route return format url
func (t *Tree) URLFor(name string, args ...interface{}) string {
if name == "" {
return ""
}
url := t.namedNodes[name]
if url == "" {
return ""
}
return fmt.Sprintf(url, args...)
}
// Add registers a new handle with the given method, pattern and handlers.
// add check training slash option.
func (t *Tree) Add(method, pattern string, handlers []HandlerFunc) RouteNode {
if method == "GET" && t.autoHead {
t.add("HEAD", pattern, handlers)
}
if t.autoTrailingSlash && (len(pattern) > 1 || len(t.groups) > 0) {
if pattern[len(pattern)-1] == '/' {
pattern = pattern[:len(pattern)-1]
}
t.add(method, pattern+"/", handlers)
}
return t.add(method, pattern, handlers)
}
// GroupAdd add a group route has same prefix and handle chain
func (t *Tree) GroupAdd(pattern string, f func(), handlers []HandlerFunc) {
g := newGroup()
g.pattern = pattern
g.handlers = handlers
t.groups = append(t.groups, g)
f()
t.groups = t.groups[:len(t.groups)-1]
}
// add registers a new request handle with the given method, pattern and handlers.
func (t *Tree) add(method, pattern string, handlers []HandlerFunc) *Leaf {
if _, ok := RouterMethods[method]; !ok {
panic("unsupport http method [" + method + "]")
}
t.mu.Lock()
defer t.mu.Unlock()
// check group set
if len(t.groups) > 0 {
var gpattern string
var ghandlers []HandlerFunc
for i := range t.groups {
gpattern += t.groups[i].pattern
if len(t.groups[i].handlers) > 0 {
ghandlers = append(ghandlers, t.groups[i].handlers...)
}
}
pattern = gpattern + pattern
ghandlers = append(ghandlers, handlers...)
handlers = ghandlers
}
// check pattern (for training slash move behind group check)
if pattern == "" {
panic("route pattern can not be emtpy!")
}
if pattern[0] != '/' {
panic("route pattern must begin /")
}
for i := 0; i < len(handlers); i++ {
handlers[i] = wrapHandlerFunc(handlers[i])
}
root := t.nodes[RouterMethods[method]]
var radix []byte
var param []byte
var i, k int
var tru *Leaf
for i = 0; i < len(pattern); i++ {
//param route
if pattern[i] == ':' {
// clear static route
if len(radix) > 0 {
root = t.insert(root, newLeaf(string(radix), nil, nil))
radix = radix[:0]
}
// set param route
param = param[:0]
k = 0
for i = i + 1; i < len(pattern); i++ {
if pattern[i] == '/' {
i--
break
}
param = append(param, pattern[i])
k++
}
if k == 0 {
panic("route pattern param is empty")
}
// check last character
if i == len(pattern) {
tru = newLeaf(":", handlers, t)
} else {
tru = newLeaf(":", nil, nil)
}
tru.param = string(param[:k])
tru.hasParam = true
root = t.insert(root, tru)
continue
}
radix = append(radix, pattern[i])
}
// static route
if len(radix) > 0 {
tru = newLeaf(string(radix), handlers, t)
t.insert(root, tru)
}
return newLeaf(pattern, handlers, t)
}
// insert build the route tree
func (t *Tree) insert(root *Leaf, node *Leaf) *Leaf {
// same route
if root.pattern == node.pattern {
if node.handlers != nil {
root.handlers = node.handlers
}
return root
}
// param route
if !root.hasParam && node.hasParam {
return root.insertChild(node)
}
var i int
if root.hasParam && !node.hasParam {
for i = range root.children {
if root.children[i].pattern == node.pattern {
if node.handlers != nil {
root.children[i].handlers = node.handlers
}
return root.children[i]
}
if root.children[i].hasPrefixString(node.pattern) > 0 {
return t.insert(root.children[i], node)
}
}
root.insertChild(node)
return node
}
// find radix
pos := root.hasPrefixString(node.pattern)
if pos == len(node.pattern) {
root.parent.deleteChild(root)
root.parent.insertChild(node)
root.resetPattern(root.pattern[pos:])
node.insertChild(root)
return node
}
node.resetPattern(node.pattern[pos:])
if pos == len(root.pattern) {
for i = range root.children {
if root.children[i].pattern == node.pattern {
if node.handlers != nil {
root.children[i].handlers = node.handlers
}
return root.children[i]
}
if root.children[i].hasPrefixString(node.pattern) > 0 {
return t.insert(root.children[i], node)
}
}
root.insertChild(node)
return node
}
// _parent root and ru has new parent
_parent := newLeaf(root.pattern[:pos], nil, t)
root.parent.deleteChild(root)
root.parent.insertChild(_parent)
root.resetPattern(root.pattern[pos:])
_parent.insertChild(root)
_parent.insertChild(node)
return node
}
// Handlers returns handlers bond with leaf
func (l *Leaf) Handlers() []HandlerFunc {
return l.handlers
}
// Name set name of route
func (l *Leaf) Name(name string) {
if name == "" {
return
}
p := make([]byte, 0, len(l.pattern))
for i := 0; i < len(l.pattern); i++ {
if l.pattern[i] != ':' {
p = append(p, l.pattern[i])
continue
}
p = append(p, '%')
p = append(p, 'v')
for i = i + 1; i < len(l.pattern); i++ {
if l.pattern[i] == '/' {
i--
break
}
}
}
l.root.namedNodes[name] = string(p)
}
// findChild find child static route
func (l *Leaf) findChild(b byte) *Leaf {
var i int
var j = len(l.children)
for ; i < j; i++ {
if l.children[i].alpha == b && !l.children[i].hasParam {
return l.children[i]
}
}
return nil
}
// deleteChild find child and delete from root route
func (l *Leaf) deleteChild(node *Leaf) {
for i := 0; i < len(l.children); i++ {
if l.children[i].pattern != node.pattern {
continue
}
if len(l.children) == 1 {
l.children = l.children[:0]
return
}
if i == 0 {
l.children = l.children[1:]
return
}
if i+1 == len(l.children) {
l.children = l.children[:i]
return
}
l.children = append(l.children[:i], l.children[i+1:]...)
return
}
}
// insertChild insert child into root route, and returns the child route
func (l *Leaf) insertChild(node *Leaf) *Leaf {
var i int
for ; i < len(l.children); i++ {
if l.children[i].pattern == node.pattern {
if l.children[i].hasParam && node.hasParam && l.children[i].param != node.param {
panic("Router Tree.insert error cannot use two param [:" + l.children[i].param + ", :" + node.param + "]with same prefix!")
}
if node.handlers != nil {
l.children[i].handlers = node.handlers
}
return l.children[i]
}
}
node.parent = l
l.children = append(l.children, node)
i = len(l.children) - 1
if i > 0 && l.children[i].hasParam {
l.children[0], l.children[i] = l.children[i], l.children[0]
return l.children[0]
}
return node
}
// resetPattern reset route pattern and alpha
func (l *Leaf) resetPattern(pattern string) {
l.pattern = pattern
l.alpha = pattern[0]
}
// hasPrefixString returns the same prefix position, if none return 0
func (l *Leaf) hasPrefixString(s string) int {
var i, j int
j = len(l.pattern)
if len(s) < j {
j = len(s)
}
for i = 0; i < j && s[i] == l.pattern[i]; i++ {
}
return i
}