-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
node.go
396 lines (331 loc) · 7.68 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
package bunrouter
import (
"fmt"
"net/http"
"sort"
"strings"
)
type node struct {
route string
part string
handlerMap *handlerMap
parent *node
colon *node
isWC bool
nodes []*node
index struct {
table []uint8 // index table for the nodes: firstChar-minChar => node position
minChar byte // min char in the table
maxChar byte // max char in the table
}
}
func (n *node) addRoute(route string) (*node, map[string]int) {
parts, params := splitRoute(route)
currNode := n
for _, part := range parts {
currNode = currNode.addPart(part)
}
if currNode.route == "" {
currNode.route = route
}
n.indexNodes()
return currNode, params
}
func (n *node) addPart(part string) *node {
if part == "*" {
n.isWC = true
return n
}
if part == ":" {
if n.colon == nil {
n.colon = &node{part: ":"}
}
return n.colon
}
for childNodeIndex, childNode := range n.nodes {
if childNode.part[0] != part[0] {
continue
}
// Check for a common prefix.
for i, c := range []byte(part) {
if i == len(childNode.part) {
break
}
if c == childNode.part[i] {
continue
}
// Create a node for the common prefix.
childNode.part = childNode.part[i:]
newNode := &node{part: part[i:]}
n.nodes[childNodeIndex] = &node{
part: part[:i], // common prefix
nodes: []*node{childNode, newNode},
}
return newNode
}
// Parts match completely.
switch {
case len(part) > len(childNode.part): // part is bigger
part = part[len(childNode.part):]
return childNode.addPart(part)
case len(part) < len(childNode.part): // part is smaller
childNode.part = childNode.part[len(part):]
newNode := &node{part: part}
newNode.nodes = []*node{childNode}
n.nodes[childNodeIndex] = newNode
return newNode
default:
return childNode // exact match
}
}
node := &node{part: part}
n.nodes = append(n.nodes, node)
return node
}
func (n *node) findRoute(meth, path string) (*node, *routeHandler, int) {
if path == "" {
return nil, nil, 0
}
path = path[1:] // strip leading "/"
if path == "" {
if n.handlerMap != nil {
return n, n.handlerMap.Get(meth), 0
}
return nil, nil, 0
}
return n._findRoute(meth, path)
}
func (n *node) _findRoute(meth, path string) (*node, *routeHandler, int) {
var found *node
if firstChar := path[0]; firstChar >= n.index.minChar && firstChar <= n.index.maxChar {
if i := n.index.table[firstChar-n.index.minChar]; i != 0 {
childNode := n.nodes[i-1]
if childNode.part == path {
if childNode.handlerMap != nil {
if handler := childNode.handlerMap.Get(meth); handler != nil {
return childNode, handler, 0
}
found = childNode
}
} else {
partLen := len(childNode.part)
if strings.HasPrefix(path, childNode.part) {
node, handler, wildcardLen := childNode._findRoute(meth, path[partLen:])
if handler != nil {
return node, handler, wildcardLen
}
if node != nil {
found = node
}
}
}
}
}
if n.colon != nil {
if i := strings.IndexByte(path, '/'); i > 0 {
node, handler, wildcardLen := n.colon._findRoute(meth, path[i:])
if handler != nil {
return node, handler, wildcardLen
}
} else if n.colon.handlerMap != nil {
if handler := n.colon.handlerMap.Get(meth); handler != nil {
return n.colon, handler, 0
}
if found == nil {
found = n.colon
}
}
}
if n.isWC && n.handlerMap != nil {
if handler := n.handlerMap.Get(meth); handler != nil {
return n, handler, len(path)
}
if found == nil {
found = n
}
}
return found, nil, 0
}
func (n *node) indexNodes() {
if len(n.nodes) > 0 {
n._indexNodes()
}
if n.colon != nil {
n.colon.parent = n
n.colon.indexNodes()
}
}
func (n *node) _indexNodes() {
sort.Slice(n.nodes, func(i, j int) bool {
return n.nodes[i].part[0] < n.nodes[j].part[0]
})
n.index.minChar = n.nodes[0].part[0]
n.index.maxChar = n.nodes[len(n.nodes)-1].part[0]
// Reset index.
if size := int(n.index.maxChar - n.index.minChar + 1); len(n.index.table) != size {
n.index.table = make([]uint8, size)
} else {
for i := range n.index.table {
n.index.table[i] = 0
}
}
// Index nodes by the first char in a part.
for childNodeIndex, childNode := range n.nodes {
childNode.parent = n
childNode.indexNodes()
firstChar := childNode.part[0] - n.index.minChar
n.index.table[firstChar] = uint8(childNodeIndex + 1)
}
}
func (n *node) setHandler(verb string, handler *routeHandler) {
if n.handlerMap == nil {
n.handlerMap = newHandlerMap()
}
n.handlerMap.Set(verb, handler)
}
//------------------------------------------------------------------------------
type routeParser struct {
segments []string
i int
acc []string
parts []string
}
func (p *routeParser) valid() bool {
return p.i < len(p.segments)
}
func (p *routeParser) next() string {
s := p.segments[p.i]
p.i++
return s
}
func (p *routeParser) accumulate(s string) {
p.acc = append(p.acc, s)
}
func (p *routeParser) finalizePart(withSlash bool) {
if part := join(p.acc, withSlash); part != "" {
p.parts = append(p.parts, part)
}
p.acc = p.acc[:0]
if p.valid() {
p.acc = append(p.acc, "")
}
}
func join(ss []string, withSlash bool) string {
if len(ss) == 0 {
return ""
}
s := strings.Join(ss, "/")
if withSlash {
return s + "/"
}
return s
}
func splitRoute(route string) (_ []string, _ map[string]int) {
if route == "" || route[0] != '/' {
panic(fmt.Errorf("invalid route: %q", route))
}
if route == "/" {
return []string{}, nil
}
route = route[1:] // trim first "/"
ss := strings.Split(route, "/")
if len(ss) == 0 {
panic(fmt.Errorf("invalid route: %q", route))
}
p := routeParser{
segments: ss,
}
var params []string
for p.valid() {
segment := p.next()
if segment == "" {
p.accumulate("")
continue
}
switch firstChar := segment[0]; firstChar {
case ':':
p.finalizePart(true)
p.parts = append(p.parts, ":")
params = append(params, segment[1:])
case '*':
p.finalizePart(true)
p.parts = append(p.parts, "*")
params = append(params, segment[1:])
default:
p.accumulate(segment)
}
}
p.finalizePart(false)
if len(params) > 0 {
return p.parts, paramMap(route, params)
}
return p.parts, nil
}
func paramMap(route string, params []string) map[string]int {
m := make(map[string]int, len(params))
for i, param := range params {
if param == "" {
panic(fmt.Errorf("param must have a name: %q", route))
}
m[param] = i
}
return m
}
//------------------------------------------------------------------------------
type handlerMap struct {
get *routeHandler
post *routeHandler
put *routeHandler
delete *routeHandler
head *routeHandler
options *routeHandler
patch *routeHandler
notAllowed *routeHandler
}
type routeHandler struct {
fn HandlerFunc
params map[string]int // param name => param position
}
func newHandlerMap() *handlerMap {
return new(handlerMap)
}
func (h *handlerMap) Get(meth string) *routeHandler {
switch meth {
case http.MethodGet:
return h.get
case http.MethodPost:
return h.post
case http.MethodPut:
return h.put
case http.MethodDelete:
return h.delete
case http.MethodHead:
return h.head
case http.MethodOptions:
return h.options
case http.MethodPatch:
return h.patch
default:
return nil
}
}
func (h *handlerMap) Set(meth string, handler *routeHandler) {
switch meth {
case http.MethodGet:
h.get = handler
case http.MethodPost:
h.post = handler
case http.MethodPut:
h.put = handler
case http.MethodDelete:
h.delete = handler
case http.MethodHead:
h.head = handler
case http.MethodOptions:
h.options = handler
case http.MethodPatch:
h.patch = handler
default:
panic(fmt.Errorf("unknown HTTP method: %s", meth))
}
}