-
Notifications
You must be signed in to change notification settings - Fork 1
/
tree.go
101 lines (80 loc) · 1.94 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
package router
import (
"strings"
)
type Tree interface {
add(path string, route *route)
find(path string) (*route, error)
exists(path string) bool
}
type tree struct {
children map[string]*tree
route *route
}
func newTree() Tree {
return &tree{}
}
func (t *tree) add(path string, route *route) {
root := t
segments := strings.Split(path, pathSeparator)
var variables []string
for idx := range segments {
segment := segments[idx]
if root.children == nil {
root.children = map[string]*tree{}
}
if isVariable(segment) {
variable := strings.TrimLeft(segment, pathVariablePrefix)
variables = append(variables, variable)
segment = pathVariablePlaceholder
}
_, exists := root.children[segment]
if !exists {
root.children[segment] = &tree{}
}
root = root.children[segment]
}
route.variables = variables
root.route = route
}
func (t *tree) find(path string) (*route, error) {
root := t
segments := strings.Split(path, pathSeparator)
var values []string
for idx := range segments {
segment := segments[idx]
_, exists := root.children[segment]
if !exists {
if _, exists = root.children[pathVariablePlaceholder]; !exists {
return nil, &routeNotFoundError{path: path}
}
values = append(values, segment)
segment = pathVariablePlaceholder
}
root = root.children[segment]
}
if root.route == nil {
return nil, &routeNotFoundError{path: path}
}
root.route.variableValues = values
return root.route, nil
}
func (t *tree) exists(path string) bool {
root := t
segments := strings.Split(path, pathSeparator)
for idx := range segments {
segment := segments[idx]
_, exists := root.children[segment]
if !exists {
if _, exists = root.children[pathVariablePlaceholder]; !exists {
return false
}
segment = pathVariablePlaceholder
}
root = root.children[segment]
}
return root.route != nil
}
func isVariable(s string) bool {
return strings.HasPrefix(s, pathVariablePrefix)
}