-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
trie.go
355 lines (311 loc) · 6.66 KB
/
trie.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
package goblin
import (
"net/http"
"path"
"regexp"
"strings"
"sync"
)
// tree is a trie tree.
type tree struct {
node *node
paramsPool sync.Pool
maxParams int
}
// node is a node of tree.
type node struct {
label string
action *action // key is method
children []*node // key is label of next nodes
}
// action is an action.
type action struct {
middlewares middlewares
handler http.Handler
}
const (
paramDelimiter string = ":"
leftPtnDelimiter string = "["
rightPtnDelimiter string = "]"
ptnWildcard string = "(.+)"
)
// newTree creates a new trie tree.
func newTree() *tree {
return &tree{
node: &node{
label: "/",
action: &action{},
children: []*node{},
},
}
}
// Param is a parameter.
type Param struct {
key string
value string
}
type Params []Param
// getParams gets parameters.
func (t *tree) getParams() *Params {
ps, _ := t.paramsPool.Get().(*Params)
*ps = (*ps)[:0] // reset slice
return ps
}
// putParams puts parameters.
func (t *tree) putParams(ps *Params) {
if ps != nil {
t.paramsPool.Put(ps)
}
}
func (n *node) getChild(label string) *node {
for i := 0; i < len(n.children); i++ {
if n.children[i].label == label {
return n.children[i]
}
}
return nil
}
// Insert inserts a route definition to tree.
func (t *tree) Insert(path string, handler http.Handler, mws middlewares) {
path = cleanPath(path)
curNode := t.node
if path == "/" {
curNode.label = path
curNode.action = &action{
middlewares: mws,
handler: handler,
}
return
}
path = removeTrailingSlash(path)
cnt := strings.Count(path, "/")
var l string
for i := 0; i < cnt; i++ {
// Delete the / at head of path. ex. /foo/bar → foo/bar
if path[:1] == "/" {
path = path[1:]
}
idx := strings.Index(path, "/")
l = path
if idx > 0 {
// ex. foo/bar/baz → foo
l = path[:idx]
}
nextNode := curNode.getChild(l)
if nextNode != nil {
curNode = nextNode
if idx > 0 {
l = path[:idx]
// foo/bar/baz → /bar/baz
path = path[idx:]
}
} else {
// Create a new node.
child := &node{
label: l,
action: &action{},
children: []*node{},
}
curNode.children = append(curNode.children, child)
curNode = child
if idx > 0 {
l = path[:idx]
// foo/bar/baz → /bar/baz
path = path[idx:]
}
}
// last loop.
// If there is already registered data, overwrite it.
if i == cnt-1 {
curNode.label = l
curNode.action = &action{
middlewares: mws,
handler: handler,
}
break
}
}
if t.maxParams < cnt {
t.maxParams = cnt
}
if t.paramsPool.New == nil && t.maxParams > 0 {
t.paramsPool.New = func() interface{} {
p := make(Params, 0, t.maxParams)
return &p
}
}
}
// regCache represents the cache for a regular expression.
type regCache struct {
s sync.Map
}
// getReg gets a compiled regexp from cache or create it.
func (rc *regCache) getReg(ptn string) (*regexp.Regexp, error) {
v, ok := rc.s.Load(ptn)
if ok {
reg, _ := v.(*regexp.Regexp)
return reg, nil
}
reg, err := regexp.Compile(ptn)
if err != nil {
return nil, err
}
rc.s.Store(ptn, reg)
return reg, nil
}
var regC = ®Cache{}
// Search searches a path from a tree.
func (t *tree) Search(path string) (*action, Params, error) {
path = cleanPath(path)
curNode := t.node
path = removeTrailingSlash(path)
cnt := strings.Count(path, "/")
var l string
var params Params
for i := 0; i < cnt; i++ {
// Delete the / at head of path. ex. /foo/bar → foo/bar
if path[:1] == "/" {
path = path[1:]
}
idx := strings.Index(path, "/")
// ex. foo → foo
l = path
if idx > 0 {
// ex. foo/bar/baz → foo
l = path[:idx]
}
cc := curNode.children
// leaf node
if len(cc) == 0 {
if curNode.label != l {
// no matching path was found.
return nil, nil, ErrNotFound
}
}
nextNode := curNode.getChild(l)
if nextNode != nil {
curNode = nextNode
if idx > 0 {
// foo/bar/baz → /bar/baz
path = path[idx:]
}
continue
}
isParamMatch := false
// parameter matching
for _, c := range cc {
if c.label[0:1] == paramDelimiter {
ptn := getPattern(c.label)
if ptn != "" {
reg, err := regC.getReg(ptn)
if err != nil {
return nil, nil, ErrNotFound
}
if !reg.Match([]byte(l)) {
return nil, nil, ErrNotFound
}
}
pn := getParamName(c.label)
if params == nil {
ps := t.getParams()
params = (*ps)[0:1]
params[0] = Param{
key: pn,
value: l,
}
t.putParams(ps)
} else {
params = append(params, Param{
key: pn,
value: l,
})
}
curNode = c
isParamMatch = true
if idx > 0 {
// ex. foo/bar/baz → /bar/baz
path = path[idx:]
}
}
}
if !isParamMatch {
// no matching path was found.
return nil, nil, ErrNotFound
}
}
action := curNode.action
if action.handler == nil {
// no matching handler and middlewares was found.
return nil, nil, ErrNotFound
}
if params == nil {
return action, nil, nil
}
return action, params, nil
}
// getPattern gets a pattern from a label.
// ex.
// :id[^\d+$] → ^\d+$
// :id → (.+)
func getPattern(label string) string {
leftI := strings.Index(label, leftPtnDelimiter)
rightI := strings.Index(label, rightPtnDelimiter)
// if label doesn't have any pattern, return wild card pattern as default.
if leftI == -1 || rightI == -1 {
return ""
}
return label[leftI+1 : rightI]
}
// getParamName gets a parameter from a label.
// ex.
// :id[^\d+$] → id
// :id → id
func getParamName(label string) string {
leftI := strings.Index(label, paramDelimiter)
rightI := func(l string) int {
var n int
for i := 0; i < len(l); i++ {
n = i
if l[i:i+1] == leftPtnDelimiter {
n = i
break
}
if i == len(l)-1 {
n = i + 1
break
}
}
return n
}(label)
return label[leftI+1 : rightI]
}
// cleanPath returns the canonical path for p, eliminating . and .. elements.
// This method borrowed from from net/http package.
// see https://cs.opensource.google/go/go/+/master:src/net/http/server.go;l=2310;bpv=1;bpt=1
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
// Fast path for common case of p being the string we want:
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
np = p
} else {
np += "/"
}
}
return np
}
// removeTrailingSlash removes trailing slash from path.
func removeTrailingSlash(path string) string {
if path[len(path)-1:] == "/" {
path = path[:len(path)-1]
}
return path
}