/
tree.go
493 lines (418 loc) · 12.8 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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Copyright 2021 Flamego. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package route
import (
"net/http"
"net/url"
"regexp"
"strings"
"github.com/pkg/errors"
)
// Tree is a tree derived from a segment.
type Tree interface {
// Match matches a leaf for the given request path, values of bind parameters
// are stored in the `Params`. The `Params` may contain extra values that do not
// belong to the final leaf due to backtrace.
Match(path string) (Leaf, Params, bool)
// getParent returns the parent tree. The root tree does not have parent.
getParent() Tree
// getSegment returns the segment that the tree is derived from.
getSegment() *Segment
// getMatchStyle returns the match style of the tree.
getMatchStyle() MatchStyle
// getSubtrees returns the list of direct subtrees.
getSubtrees() []Tree
// getLeaves returns the list of direct leaves.
getLeaves() []Leaf
// setSubtrees sets the list of direct subtrees.
setSubtrees(subtrees []Tree)
// setLeaves sets the list of direct leaves.
setLeaves(leaves []Leaf)
// getBinds returns the list of bind parameters.
getBinds() []string
// hasMatchAllSubtree returns true if there is on match all style subtree exists.
hasMatchAllSubtree() bool
// hasMatchAllLeaf returns true if there is on match all style leaf exists.
hasMatchAllLeaf() bool
// match returns true if the tree matches the segment, values of bind parameters
// are stored in the `Params`. The `Params` may contain extra values that do not
// belong to the final leaf due to backtrace.
match(segment string, params Params) bool
// matchNextSegment advances the `next` cursor for matching next segment in the
// request path.
matchNextSegment(path string, next int, params Params) (Leaf, bool)
}
// baseTree contains common fields and methods for any tree.
type baseTree struct {
parent Tree // The parent tree.
segment *Segment // The segment that the tree is derived from.
subtrees []Tree // The list of direct subtrees ordered by matching priority.
leaves []Leaf // The list of direct leaves ordered by matching priority.
}
func (t *baseTree) getParent() Tree {
return t.parent
}
func (t *baseTree) getSegment() *Segment {
return t.segment
}
func (t *baseTree) getMatchStyle() MatchStyle {
return matchStyleNone
}
func (t *baseTree) getSubtrees() []Tree {
return t.subtrees
}
func (t *baseTree) getLeaves() []Leaf {
return t.leaves
}
func (t *baseTree) setSubtrees(subtrees []Tree) {
t.subtrees = subtrees
}
func (t *baseTree) setLeaves(leaves []Leaf) {
t.leaves = leaves
}
func (t *baseTree) getBinds() []string {
return nil
}
func (t *baseTree) hasMatchAllSubtree() bool {
return len(t.subtrees) > 0 &&
t.subtrees[len(t.subtrees)-1].getMatchStyle() == matchStyleAll
}
func (t *baseTree) hasMatchAllLeaf() bool {
return len(t.leaves) > 0 &&
t.leaves[len(t.leaves)-1].getMatchStyle() == matchStyleAll
}
func (t *baseTree) match(_ string, _ Params) bool {
panic("unreachable")
}
// Params is a set of bind parameters with their values that are extracted from
// the request path.
type Params map[string]string
// Handler is a function that can be registered to a route for handling HTTP
// requests.
type Handler func(http.ResponseWriter, *http.Request, Params)
// addLeaf adds a new leaf from the given segment.
func addLeaf(t Tree, r *Route, s *Segment, h Handler) (Leaf, error) {
leaves := t.getLeaves()
for _, l := range leaves {
if l.getSegment().String() == s.String() {
return nil, errors.Errorf("duplicated route %q", r.String())
}
}
leaf, err := newLeaf(t, r, s, h)
if err != nil {
return nil, errors.Wrap(err, "new leaf")
}
// At most one match all style leaf can exist in a leaf list.
if leaf.getMatchStyle() == matchStyleAll &&
t.hasMatchAllLeaf() {
return nil, errors.Errorf("duplicated match all bind parameter in position %d", s.Pos.Offset)
}
if leaf.getSegment().Optional {
parent := leaf.getParent()
if parent.getParent() != nil {
_, err = addLeaf(parent.getParent(), r, parent.getSegment(), h)
if err != nil {
return nil, errors.Wrap(err, "add optional leaf to grandparent")
}
} else {
_, err = addLeaf(parent, r, parent.getSegment(), h)
if err != nil {
return nil, errors.Wrap(err, "add optional leaf to parent")
}
}
}
// Determine leaf position by the priority of match styles.
i := 0
for ; i < len(leaves); i++ {
if leaf.getMatchStyle() < leaves[i].getMatchStyle() {
break
}
}
if i == len(leaves) {
leaves = append(leaves, leaf)
} else {
leaves = append(leaves[:i], append([]Leaf{leaf}, leaves[i:]...)...)
}
t.setLeaves(leaves)
return leaf, nil
}
// addSubtree adds a new subtree from next segment of the route.
func addSubtree(t Tree, r *Route, next int, h Handler) (Leaf, error) {
segment := r.Segments[next]
for _, st := range t.getSubtrees() {
if st.getSegment().String() == segment.String() {
return addNextSegment(st, r, next+1, h)
}
}
subtree, err := newTree(t, segment)
if err != nil {
return nil, errors.Wrap(err, "new tree")
}
// At most one match all style subtree can exist in a subtree list.
if subtree.getMatchStyle() == matchStyleAll &&
t.hasMatchAllSubtree() {
return nil, errors.Errorf("duplicated match all bind parameter in position %d", segment.Pos.Offset)
}
// Determine subtree position by the priority of match styles.
subtrees := t.getSubtrees()
i := 0
for ; i < len(subtrees); i++ {
if subtree.getMatchStyle() < subtrees[i].getMatchStyle() {
break
}
}
if i == len(subtrees) {
subtrees = append(subtrees, subtree)
} else {
subtrees = append(subtrees[:i], append([]Tree{subtree}, subtrees[i:]...)...)
}
t.setSubtrees(subtrees)
return addNextSegment(subtree, r, next+1, h)
}
// addNextSegment adds next segment of the route to the tree.
func addNextSegment(t Tree, r *Route, next int, h Handler) (Leaf, error) {
if len(r.Segments) <= next+1 {
return addLeaf(t, r, r.Segments[next], h)
}
if r.Segments[next].Optional {
return nil, errors.New("only the last segment can be optional")
}
return addSubtree(t, r, next, h)
}
// staticTree is a tree with a static match style.
type staticTree struct {
baseTree
}
func (t *staticTree) getMatchStyle() MatchStyle {
return matchStyleStatic
}
func (t *staticTree) getBinds() []string {
return nil
}
func (t *staticTree) match(segment string, _ Params) bool {
return t.segment.String()[1:] == segment // Skip the leading "/"
}
// regexTree is a tree with a regex match style.
type regexTree struct {
baseTree
regexp *regexp.Regexp // The regexp for the tree.
binds []string // The list of bind parameters.
}
func (t *regexTree) getMatchStyle() MatchStyle {
return matchStyleRegex
}
func (t *regexTree) getBinds() []string {
binds := make([]string, len(t.binds))
copy(binds, t.binds)
return binds
}
func (t *regexTree) match(segment string, params Params) bool {
submatches := t.regexp.FindStringSubmatch(segment)
if len(submatches) != len(t.binds)+1 {
return false
}
for i, bind := range t.binds {
params[bind] = submatches[i+1]
}
return true
}
// placeholderTree is a tree with a placeholder match style.
type placeholderTree struct {
baseTree
bind string // The name of the bind parameter.
}
func (t *placeholderTree) getMatchStyle() MatchStyle {
return matchStylePlaceholder
}
func (t *placeholderTree) getBinds() []string {
return []string{t.bind}
}
func (t *placeholderTree) match(segment string, params Params) bool {
params[t.bind] = segment
return true
}
// placeholderTree is a tree with a match all style.
type matchAllTree struct {
baseTree
bind string // The name of the bind parameter.
capture int // The capture limit of the bind parameter. Non-positive means unlimited.
}
func (t *matchAllTree) getMatchStyle() MatchStyle {
return matchStyleAll
}
func (t *matchAllTree) getBinds() []string {
return []string{t.bind}
}
// matchAll matches all remaining segments up to the capture limit (when
// defined). The `path` should be original request path, `segment` should NOT be
// unescaped by the caller. It returns the matched leaf and true if segments are
// captured within the limit, and the capture result is stored in `params`.
func (t *matchAllTree) matchAll(path string, segment string, next int, params Params) (Leaf, bool) {
captured := 1 // Starts with 1 because the segment itself also count.
for t.capture <= 0 || t.capture >= captured {
leaf, ok := t.matchNextSegment(path, next, params)
if ok {
params[t.bind] = segment
return leaf, true
}
i := strings.Index(path[next:], "/")
if i == -1 {
// We've reached last segment of the request path, but it should be matched by a
// leaf not a subtree by definition.
break
}
segment += "/" + path[next:next+i]
next += i + 1
captured++
}
return nil, false
}
// newTree creates and returns a new Tree derived from the given segment.
func newTree(parent Tree, s *Segment) (Tree, error) {
if len(s.Elements) == 0 {
return nil, errors.Errorf("empty segment in position %d", s.Pos.Offset)
}
if isMatchStyleStatic(s) {
return &staticTree{
baseTree: baseTree{
parent: parent,
segment: s,
},
}, nil
}
parentBindSet := getParentBindSet(parent)
if bind, ok := checkMatchStylePlaceholder(s); ok {
if _, exists := parentBindSet[bind]; exists {
return nil, errors.Errorf("duplicated bind parameter %q in position %d", bind, s.Pos.Offset)
}
return &placeholderTree{
baseTree: baseTree{
parent: parent,
segment: s,
},
bind: bind,
}, nil
}
if bind, capture, ok := checkMatchStyleAll(s); ok {
if _, exists := parentBindSet[bind]; exists {
return nil, errors.Errorf("duplicated bind parameter %q in position %d", bind, s.Pos.Offset)
}
// One route can only have at most one match all style for subtree.
ancestor := parent
for ancestor != nil {
if ancestor.getMatchStyle() == matchStyleAll {
return nil, errors.Errorf("duplicated match all style in position %d", s.Pos.Offset)
}
ancestor = ancestor.getParent()
}
return &matchAllTree{
baseTree: baseTree{
parent: parent,
segment: s,
},
bind: bind,
capture: capture,
}, nil
}
// The only remaining style is regex.
re, binds, err := constructMatchStyleRegex(s)
if err != nil {
return nil, err
}
for _, bind := range binds {
if _, exists := parentBindSet[bind]; exists {
return nil, errors.Errorf("duplicated bind parameter %q in position %d", bind, s.Pos.Offset)
}
}
return ®exTree{
baseTree: baseTree{
parent: parent,
segment: s,
},
regexp: re,
binds: binds,
}, nil
}
// NewTree creates and returns a root tree.
func NewTree() Tree {
return &baseTree{}
}
// AddRoute adds a new route to the tree and associates the given handler.
func AddRoute(t Tree, r *Route, h Handler) (Leaf, error) {
if r == nil || len(r.Segments) == 0 {
return nil, errors.New("cannot add empty route")
}
return addNextSegment(t, r, 0, h)
}
// matchLeaf returns the matched leaf and true if any leaf of the tree matches
// the given segment.
func (t *baseTree) matchLeaf(segment string, params Params) (Leaf, bool) {
for _, l := range t.leaves {
ok := l.match(segment, params)
if ok {
return l, true
}
}
return nil, false
}
// matchSubtree returns the matched leaf and true if any subtree or leaf of the
// tree matches the given segment.
func (t *baseTree) matchSubtree(path string, segment string, next int, params Params) (Leaf, bool) {
for _, st := range t.subtrees {
if st.getMatchStyle() == matchStyleAll {
leaf, ok := st.(*matchAllTree).matchAll(path, segment, next, params)
if ok {
return leaf, true
}
// Any list of subtrees only has at most one match all style as the last
// element. Therefore both "break" and "continue" have the same effect, but
// using "break" here to be explicit.
break
}
ok := st.match(segment, params)
if !ok {
continue
}
leaf, ok := st.matchNextSegment(path, next, params)
if !ok {
continue
}
return leaf, true
}
// Fall back to match all leaf of the tree.
if len(t.leaves) > 0 {
leaf := t.leaves[len(t.leaves)-1]
if leaf.getMatchStyle() != matchStyleAll {
return nil, false
}
ok := leaf.(*matchAllLeaf).matchAll(path, segment, next, params)
if ok {
return leaf, ok
}
return nil, false
}
return nil, false
}
func (t *baseTree) matchNextSegment(path string, next int, params Params) (Leaf, bool) {
i := strings.Index(path[next:], "/")
if i == -1 {
return t.matchLeaf(path[next:], params)
}
return t.matchSubtree(path, path[next:next+i], next+i+1, params)
}
func (t *baseTree) Match(path string) (Leaf, Params, bool) {
path = strings.TrimLeft(path, "/")
params := make(Params)
leaf, ok := t.matchNextSegment(path, 0, params)
if !ok {
return nil, nil, false
}
for k, v := range params {
unescaped, err := url.PathUnescape(v)
if err == nil {
params[k] = unescaped
}
}
return leaf, params, true
}