forked from gin-gonic/gin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.go
321 lines (270 loc) · 7.88 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
package gin
import (
"fmt"
"net/url"
"strings"
)
// Param is a single URL parameter, consisting of a key and a value.
type Param struct {
Key string
Value string
}
// Params is a Param-slice, as returned by the router.
// The slice is ordered, the first URL parameter is also the first slice value.
// It is therefore safe to read values by the index.
type Params []Param
// ByName returns the value of the first Param which key matches the given name.
// If no matching Param is found, an empty string is returned.
func (ps Params) Get(name string) (string, bool) {
for _, entry := range ps {
if entry.Key == name {
return entry.Value, true
}
}
return "", false
}
func (ps Params) ByName(name string) (va string) {
va, _ = ps.Get(name)
return
}
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 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) setHandlers(verb string, handlers ...HandlerFunc) {
if n.leafHandler == nil {
n.leafHandler = make(map[string][]HandlerFunc)
}
n.leafHandler[verb] = append(n.leafHandler[verb], handlers...)
}
func (n *node) addPath(path string, wildcards []string) *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 == '/' {
thisToken = "/"
tokenEnd = 1
} else if nextSlash == -1 {
thisToken = path
tokenEnd = len(path)
} else {
thisToken = path[0:nextSlash]
tokenEnd = nextSlash
}
remainingPath := path[tokenEnd:]
if c == '*' {
// 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",
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 == ':' {
// 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)
} else {
if strings.ContainsAny(thisToken, ":*") {
panic("* or : in middle of path component " + path)
}
// 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)
return child.addPath(path[prefixSplit:], wildcards)
}
}
// 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)
}
}
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(path string) (found *node, 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
} else {
return n, 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, params = child.search(nextPath)
}
break
}
}
if found != nil {
return
}
if n.wildcardChild != nil {
// Didn't find a static token, so check for a wildcard.
nextSlash := 0
for nextSlash < pathLen && path[nextSlash] != '/' {
nextSlash++
}
thisToken := path[0:nextSlash]
nextToken := path[nextSlash:]
if len(thisToken) > 0 { // Don't match on empty tokens.
found, params = n.wildcardChild.search(nextToken)
if found != nil {
unescaped, err := url.QueryUnescape(thisToken)
if err != nil {
unescaped = thisToken
}
if params == nil {
params = []string{unescaped}
} else {
params = append(params, unescaped)
}
return
}
}
}
catchAllChild := n.catchAllChild
if catchAllChild != nil {
// Hit the catchall, so just assign the whole remaining path.
unescaped, err := url.QueryUnescape(path)
if err != nil {
unescaped = path
}
return catchAllChild, []string{unescaped}
}
return nil, nil
}
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
}