-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtree.go
59 lines (55 loc) · 1.21 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
package sgo
import (
"net/url"
"strings"
)
// Trie node.
type Trie struct {
children []*Trie
param byte
component string
methods map[string]HandlerFunc
}
// Insert a node into the tree.
func (t *Trie) Insert(method, path string, handler HandlerFunc) {
components := strings.Split(path, "/")[1:]
Next:
for _, component := range components {
for _, child := range t.children {
if child.component == component {
t = child
continue Next
}
}
newNode := &Trie{component: component,
methods: make(map[string]HandlerFunc)}
if len(component) > 0 {
if component[0] == ':' || component[0] == '*' {
newNode.param = component[0]
}
}
t.children = append(t.children, newNode)
t = newNode
}
t.methods[method] = handler
}
// Search the tree.
func (t *Trie) Search(components []string, params url.Values) *Trie {
Next:
for _, component := range components {
for _, child := range t.children {
if child.component == component || child.param == ':' || child.param == '*' {
if child.param == '*' {
return child
}
if child.param == ':' {
params.Add(child.component[1:], component)
}
t = child
continue Next
}
}
return nil // not found
}
return t
}