-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
88 lines (78 loc) · 1.39 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
package gRouter
import "regexp"
var (
methodList = []string{
"POST",
"GET",
"HEAD",
"OPTIONS",
"PUT",
"DELETE",
"PATCH",
"CONNECT",
"TRACE",
}
)
type tree struct {
method string
root *node
}
func newTree(method string) *tree {
if isDebug {
checkMethod(method)
}
return &tree{
method: method,
root: newNode("", true),
}
}
func checkMethod(method string) {
for i := 0; i < len(methodList); i++ {
if methodList[i] == method {
return
}
}
panic("method is error")
}
func checkUrl(url string) {
rule := "[a-zA-Z0-9-._~!$&'/()*+,;=:]*"
reg, err := regexp.Compile(rule)
if err != nil {
panic(err)
}
if !reg.Match([]byte(url)) {
panic(errorUrlFormat)
}
}
func (tree *tree) Add(url string, handlers HandlersChain) error {
if isDebug {
checkUrl(url)
}
return tree.root.Add(url, handlers)
}
func (tree *tree) Find(url string) (*node, error) {
return tree.root.Find(url)
}
func (tree *tree) PathList() []string {
list := make([]string, 0)
tree.pathList(&list, tree.root, "")
return list
}
func (tree *tree) pathList(list *[]string, root *node, subPath string) {
if root == nil {
return
}
if root.path != "" {
subPath += "/" + root.path
}
if root.isLeaf {
if root.isRoot {
*list = append(*list, "/")
} else {
*list = append(*list, subPath)
}
}
for i := 0; i < len(root.children); i++ {
tree.pathList(list, root.children[i], subPath)
}
}