-
Notifications
You must be signed in to change notification settings - Fork 26
/
node.go
419 lines (337 loc) · 9.72 KB
/
node.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
// Copyright 2016 Dean Karn.
// Copyright 2013 Julien Schmidt.
// All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at https://raw.githubusercontent.com/julienschmidt/httprouter/master/LICENSE.
package lars
import "net/url"
type nodeType uint8
const (
isRoot nodeType = iota + 1
hasParams
matchesAny
)
type methodChain struct {
handlerName string
chain HandlersChain
}
type existingParams map[string]struct{}
type node struct {
path string
indices string
children []*node
handler *methodChain
priority uint32
nType nodeType
wildChild bool
}
func (e existingParams) Check(param string, path string) {
if _, ok := e[param]; ok {
panic("Duplicate param name '" + param + "' detected for route '" + path + "'")
}
e[param] = struct{}{}
}
// increments priority of the given child and reorders if necessary
func (n *node) incrementChildPrio(pos int) int {
n.children[pos].priority++
prio := n.children[pos].priority
// adjust position (move to front)
newPos := pos
for newPos > 0 && n.children[newPos-1].priority < prio {
// swap node positions
tmpN := n.children[newPos-1]
n.children[newPos-1] = n.children[newPos]
n.children[newPos] = tmpN
newPos--
}
// build new index char string
if newPos != pos {
n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
n.indices[pos:pos+1] + // the index char we move
n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
}
return newPos
}
// addRoute adds a node with the given handle to the path.
// here we set a Middleware because we have to transfer all route's middlewares (it's a chain of functions) (with it's handler) to the node
func (n *node) add(path string, handlerName string, handler HandlersChain) (lp uint8) {
var err error
if path == blank {
path = basePath
}
existing := make(existingParams)
fullPath := path
if path, err = url.QueryUnescape(path); err != nil {
panic("Query Unescape Error on path '" + fullPath + "': " + err.Error())
}
fullPath = path
n.priority++
numParams := countParams(path)
lp = numParams
// non-empty tree
if len(n.path) > 0 || len(n.children) > 0 {
walk:
for {
// Find the longest common prefix.
// This also implies that the common prefix contains no : or *
// since the existing key can't contain those chars.
i := 0
max := min(len(path), len(n.path))
for i < max && path[i] == n.path[i] {
i++
}
// Split edge
if i < len(n.path) {
child := node{
path: n.path[i:],
wildChild: n.wildChild,
indices: n.indices,
children: n.children,
handler: n.handler,
priority: n.priority - 1,
}
n.children = []*node{&child}
// []byte for proper unicode char conversion, see httprouter #65
n.indices = string([]byte{n.path[i]})
n.path = path[:i]
n.handler = nil
n.wildChild = false
}
// Make new node a child of this node
if i < len(path) {
path = path[i:]
if n.wildChild {
n = n.children[0]
n.priority++
numParams--
existing.Check(n.path, fullPath)
// Check if the wildcard matches
if len(path) >= len(n.path) && n.path == path[:len(n.path)] {
// check for longer wildcard, e.g. :name and :names
if len(n.path) >= len(path) || path[len(n.path)] == slashByte {
continue walk
}
}
panic("path segment '" + path +
"' conflicts with existing wildcard '" + n.path +
"' in path '" + fullPath + "'")
}
c := path[0]
// slash after param
if n.nType == hasParams && c == slashByte && len(n.children) == 1 {
n = n.children[0]
n.priority++
continue walk
}
// Check if a child with the next path byte exists
for i := 0; i < len(n.indices); i++ {
if c == n.indices[i] {
i = n.incrementChildPrio(i)
n = n.children[i]
continue walk
}
}
// Otherwise insert it
if c != paramByte && c != wildByte {
// []byte for proper unicode char conversion, see httprouter #65
n.indices += string([]byte{c})
child := &node{}
n.children = append(n.children, child)
n.incrementChildPrio(len(n.indices) - 1)
n = child
}
n.insertChild(numParams, existing, path, fullPath, handlerName, handler)
return
} else if i == len(path) { // Make node a (in-path) leaf
if n.handler != nil {
panic("handlers are already registered for path '" + fullPath + "'")
}
n.handler = &methodChain{
handlerName: handlerName,
chain: handler,
}
}
return
}
} else { // Empty tree
n.insertChild(numParams, existing, path, fullPath, handlerName, handler)
n.nType = isRoot
}
return
}
func (n *node) insertChild(numParams uint8, existing existingParams, path string, fullPath string, handlerName string, handler HandlersChain) {
var offset int // already handled bytes of the path
// find prefix until first wildcard (beginning with paramByte' or wildByte')
for i, max := 0, len(path); numParams > 0; i++ {
c := path[i]
if c != paramByte && c != wildByte {
continue
}
// find wildcard end (either '/' or path end)
end := i + 1
for end < max && path[end] != slashByte {
switch path[end] {
// the wildcard name must not contain ':' and '*'
case paramByte, wildByte:
panic("only one wildcard per path segment is allowed, has: '" +
path[i:] + "' in path '" + fullPath + "'")
default:
end++
}
}
// check if this Node existing children which would be
// unreachable if we insert the wildcard here
if len(n.children) > 0 {
panic("wildcard route '" + path[i:end] +
"' conflicts with existing children in path '" + fullPath + "'")
}
if c == paramByte { // param
// check if the wildcard has a name
if end-i < 2 {
panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
}
// split path at the beginning of the wildcard
if i > 0 {
n.path = path[offset:i]
offset = i
}
child := &node{
nType: hasParams,
}
n.children = []*node{child}
n.wildChild = true
n = child
n.priority++
numParams--
// if the path doesn't end with the wildcard, then there
// will be another non-wildcard subpath starting with '/'
if end < max {
existing.Check(path[offset:end], fullPath)
n.path = path[offset:end]
offset = end
child := &node{
priority: 1,
}
n.children = []*node{child}
n = child
}
} else { // catchAll
if end != max || numParams > 1 {
panic("Character after the * symbol is not permitted, path '" + fullPath + "'")
}
if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
}
// currently fixed width 1 for '/'
i--
if path[i] != slashByte {
panic("no / before catch-all in path '" + fullPath + "'")
}
n.path = path[offset:i]
// first node: catchAll node with empty path
child := &node{
wildChild: true,
nType: matchesAny,
}
n.children = []*node{child}
n.indices = string(path[i])
n = child
n.priority++
// second node: node holding the variable
child = &node{
path: path[i:],
nType: matchesAny,
handler: &methodChain{handlerName: handlerName, chain: handler},
priority: 1,
}
n.children = []*node{child}
return
}
}
if n.nType == hasParams {
existing.Check(path[offset:], fullPath)
}
// insert remaining path part and handle to the leaf
n.path = path[offset:]
n.handler = &methodChain{handlerName: handlerName, chain: handler}
}
// Returns the handle registered with the given path (key).
func (n *node) find(path string, po Params) (handler HandlersChain, p Params, handlerName string) {
p = po
walk: // Outer loop for walking the tree
for {
if len(path) > len(n.path) {
if path[:len(n.path)] == n.path {
path = path[len(n.path):]
// If this node does not have a wildcard (param or catchAll)
// child, we can just look up the next child node and continue
// to walk down the tree
if !n.wildChild {
c := path[0]
for i := 0; i < len(n.indices); i++ {
if c == n.indices[i] {
n = n.children[i]
continue walk
}
}
return
}
// handle wildcard child
n = n.children[0]
switch n.nType {
case hasParams:
// find param end (either '/' or path end)
end := 0
for end < len(path) && path[end] != slashByte {
end++
}
// save param value
i := len(p)
p = p[:i+1] // expand slice within preallocated capacity
p[i].Key = n.path[1:]
p[i].Value = path[:end]
// we need to go deeper!
if end < len(path) {
if len(n.children) > 0 {
path = path[end:]
n = n.children[0]
continue walk
}
return
}
if n.handler != nil {
handler = n.handler.chain
handlerName = n.handler.handlerName
return
} else if len(n.children) == 1 {
// No handle found. Check if a handle for this path
n = n.children[0]
}
return
case matchesAny:
// save param value
i := len(p)
p = p[:i+1] // expand slice within preallocated capacity
p[i].Key = WildcardParam
p[i].Value = path[1:]
handler = n.handler.chain
handlerName = n.handler.handlerName
return
// can't happen, but left here in case I'm wrong
// default:
// panic("invalid node type")
}
}
} else if path == n.path {
// We should have reached the node containing the handle.
// Check if this node has a handle registered.
if n.handler != nil {
if handler, handlerName = n.handler.chain, n.handler.handlerName; handler != nil {
return
}
}
}
// Nothing found
return
}
}