forked from dimfeld/httptreemux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
340 lines (288 loc) · 9.08 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
package httptreemux
import (
"fmt"
"strings"
)
type node struct {
path string
priority int
// The list of static children to check.
staticIndices []byte
staticChild []*node
// If none of the above match, check the wildcard children
wildcardChild *node
// If none of the above match, then we use the catch-all, if applicable.
catchAllChild *node
// Data for the node is below.
addSlash bool
isCatchAll bool
// If true, the head handler was set implicitly, so let it also be set explicitly.
implicitHead bool
// If this node is the end of the URL, then call the handler, if applicable.
leafHandler map[string]HandlerFunc
// The names of the parameters to apply.
leafWildcardNames []string
}
func (n *node) sortStaticChild(i int) {
for i > 0 && n.staticChild[i].priority > n.staticChild[i-1].priority {
n.staticChild[i], n.staticChild[i-1] = n.staticChild[i-1], n.staticChild[i]
n.staticIndices[i], n.staticIndices[i-1] = n.staticIndices[i-1], n.staticIndices[i]
i -= 1
}
}
func (n *node) setHandler(verb string, handler HandlerFunc, implicitHead bool) {
if n.leafHandler == nil {
n.leafHandler = make(map[string]HandlerFunc)
}
_, ok := n.leafHandler[verb]
if ok && (verb != "HEAD" || !n.implicitHead) {
panic(fmt.Sprintf("%s already handles %s", n.path, verb))
}
n.leafHandler[verb] = handler
if verb == "HEAD" {
n.implicitHead = implicitHead
}
}
func (n *node) addPath(path string, wildcards []string, inStaticToken bool) *node {
leaf := len(path) == 0
if leaf {
if wildcards != nil {
// Make sure the current wildcards are the same as the old ones.
// If not then we have an ambiguous path.
if n.leafWildcardNames != nil {
if len(n.leafWildcardNames) != len(wildcards) {
// This should never happen.
panic("Reached leaf node with differing wildcard array length. Please report this as a bug.")
}
for i := 0; i < len(wildcards); i++ {
if n.leafWildcardNames[i] != wildcards[i] {
panic(fmt.Sprintf("Wildcards %v are ambiguous with wildcards %v",
n.leafWildcardNames, wildcards))
}
}
} else {
// No wildcards yet, so just add the existing set.
n.leafWildcardNames = wildcards
}
}
return n
}
c := path[0]
nextSlash := strings.Index(path, "/")
var thisToken string
var tokenEnd int
if c == '/' {
// Done processing the previous token, so reset inStaticToken to false.
thisToken = "/"
tokenEnd = 1
} else if nextSlash == -1 {
thisToken = path
tokenEnd = len(path)
} else {
thisToken = path[0:nextSlash]
tokenEnd = nextSlash
}
remainingPath := path[tokenEnd:]
if c == '*' && !inStaticToken {
// Token starts with a *, so it's a catch-all
thisToken = thisToken[1:]
if n.catchAllChild == nil {
n.catchAllChild = &node{path: thisToken, isCatchAll: true}
}
if path[1:] != n.catchAllChild.path {
panic(fmt.Sprintf("Catch-all name in %s doesn't match %s. You probably tried to define overlapping catchalls",
path, n.catchAllChild.path))
}
if nextSlash != -1 {
panic("/ after catch-all found in " + path)
}
if wildcards == nil {
wildcards = []string{thisToken}
} else {
wildcards = append(wildcards, thisToken)
}
n.catchAllChild.leafWildcardNames = wildcards
return n.catchAllChild
} else if c == ':' && !inStaticToken {
// Token starts with a :
thisToken = thisToken[1:]
if wildcards == nil {
wildcards = []string{thisToken}
} else {
wildcards = append(wildcards, thisToken)
}
if n.wildcardChild == nil {
n.wildcardChild = &node{path: "wildcard"}
}
return n.wildcardChild.addPath(remainingPath, wildcards, false)
} else {
// if strings.ContainsAny(thisToken, ":*") {
// panic("* or : in middle of path component " + path)
// }
unescaped := false
if len(thisToken) >= 2 && !inStaticToken {
if thisToken[0] == '\\' && (thisToken[1] == '*' || thisToken[1] == ':' || thisToken[1] == '\\') {
// The token starts with a character escaped by a backslash. Drop the backslash.
c = thisToken[1]
thisToken = thisToken[1:]
unescaped = true
}
}
// Set inStaticToken to ensure that the rest of this token is not mistaken
// for a wildcard if a prefix split occurs at a '*' or ':'.
inStaticToken = (c != '/')
// Do we have an existing node that starts with the same letter?
for i, index := range n.staticIndices {
if c == index {
// Yes. Split it based on the common prefix of the existing
// node and the new one.
child, prefixSplit := n.splitCommonPrefix(i, thisToken)
child.priority++
n.sortStaticChild(i)
if unescaped {
// Account for the removed backslash.
prefixSplit++
}
return child.addPath(path[prefixSplit:], wildcards, inStaticToken)
}
}
// No existing node starting with this letter, so create it.
child := &node{path: thisToken}
if n.staticIndices == nil {
n.staticIndices = []byte{c}
n.staticChild = []*node{child}
} else {
n.staticIndices = append(n.staticIndices, c)
n.staticChild = append(n.staticChild, child)
}
return child.addPath(remainingPath, wildcards, inStaticToken)
}
}
func (n *node) splitCommonPrefix(existingNodeIndex int, path string) (*node, int) {
childNode := n.staticChild[existingNodeIndex]
if strings.HasPrefix(path, childNode.path) {
// No split needs to be done. Rather, the new path shares the entire
// prefix with the existing node, so the new node is just a child of
// the existing one. Or the new path is the same as the existing path,
// which means that we just move on to the next token. Either way,
// this return accomplishes that
return childNode, len(childNode.path)
}
var i int
// Find the length of the common prefix of the child node and the new path.
for i = range childNode.path {
if i == len(path) {
break
}
if path[i] != childNode.path[i] {
break
}
}
commonPrefix := path[0:i]
childNode.path = childNode.path[i:]
// Create a new intermediary node in the place of the existing node, with
// the existing node as a child.
newNode := &node{
path: commonPrefix,
priority: childNode.priority,
// Index is the first letter of the non-common part of the path.
staticIndices: []byte{childNode.path[0]},
staticChild: []*node{childNode},
}
n.staticChild[existingNodeIndex] = newNode
return newNode, i
}
func (n *node) search(method, path string) (found *node, handler HandlerFunc, params []string) {
// if test != nil {
// test.Logf("Searching for %s in %s", path, n.dumpTree("", ""))
// }
pathLen := len(path)
if pathLen == 0 {
if len(n.leafHandler) == 0 {
return nil, nil, nil
} else {
return n, n.leafHandler[method], nil
}
}
// First see if this matches a static token.
firstChar := path[0]
for i, staticIndex := range n.staticIndices {
if staticIndex == firstChar {
child := n.staticChild[i]
childPathLen := len(child.path)
if pathLen >= childPathLen && child.path == path[:childPathLen] {
nextPath := path[childPathLen:]
found, handler, params = child.search(method, nextPath)
}
break
}
}
// If we found a node and it had a valid handler, then return here. Otherwise
// let's remember that we found this one, but look for a better match.
if handler != nil {
return
}
if n.wildcardChild != nil {
// Didn't find a static token, so check for a wildcard.
nextSlash := strings.IndexByte(path, '/')
if nextSlash < 0 {
nextSlash = pathLen
}
thisToken := path[0:nextSlash]
nextToken := path[nextSlash:]
if len(thisToken) > 0 { // Don't match on empty tokens.
wcNode, wcHandler, wcParams := n.wildcardChild.search(method, nextToken)
if wcHandler != nil || (found == nil && wcNode != nil) {
unescaped, err := unescape(thisToken)
if err != nil {
unescaped = thisToken
}
if wcParams == nil {
wcParams = []string{unescaped}
} else {
wcParams = append(wcParams, unescaped)
}
if wcHandler != nil {
return wcNode, wcHandler, wcParams
}
// Didn't actually find a handler here, so remember that we
// found a node but also see if we can fall through to the
// catchall.
found = wcNode
handler = wcHandler
params = wcParams
}
}
}
catchAllChild := n.catchAllChild
if catchAllChild != nil {
// Hit the catchall, so just assign the whole remaining path if it
// has a matching handler.
handler = catchAllChild.leafHandler[method]
// Found a handler, or we found a catchall node without a handler.
// Either way, return it since there's nothing left to check after this.
if handler != nil || found == nil {
unescaped, err := unescape(path)
if err != nil {
unescaped = path
}
return catchAllChild, handler, []string{unescaped}
}
}
return found, handler, params
}
func (n *node) dumpTree(prefix, nodeType string) string {
line := fmt.Sprintf("%s %02d %s%s [%d] %v wildcards %v\n", prefix, n.priority, nodeType, n.path,
len(n.staticChild), n.leafHandler, n.leafWildcardNames)
prefix += " "
for _, node := range n.staticChild {
line += node.dumpTree(prefix, "")
}
if n.wildcardChild != nil {
line += n.wildcardChild.dumpTree(prefix, ":")
}
if n.catchAllChild != nil {
line += n.catchAllChild.dumpTree(prefix, "*")
}
return line
}