-
Notifications
You must be signed in to change notification settings - Fork 9
/
trie.go
75 lines (68 loc) · 2.21 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
package helm
import (
"net/http"
"net/url"
"strings"
)
// route is a handler for an HTTP verb, plus it's middleware (if any).
type route struct {
handler http.HandlerFunc
middleware []HandlerFunc
}
// node represents a struct of each node in the tree.
type node struct {
children []*node
component string
isNamedParam bool
methods map[string]*route
}
// addNode - adds a node to our tree. Will add multiple nodes if path
// can be broken up into multiple components. Those nodes will have no
// handler implemented and will fall through to the default handler.
func (n *node) addNode(method, path string, handler http.HandlerFunc, middleware ...HandlerFunc) {
components := strings.Split(path, "/")[1:]
count := len(components)
for {
aNode, component := n.traverse(components, nil)
if aNode.component == component && count == 1 { // update an existing node.
r := route{handler: handler}
r.middleware = append(r.middleware, middleware...)
aNode.methods[method] = &r
return
}
newNode := node{component: component, isNamedParam: false, methods: make(map[string]*route)}
if len(component) > 0 && component[0] == ':' { // check if it is a named param.
newNode.isNamedParam = true
}
if count == 1 { // this is the last component of the url resource, so it gets the handler.
r := route{handler: handler}
r.middleware = append(r.middleware, middleware...)
newNode.methods[method] = &r
}
aNode.children = append(aNode.children, &newNode)
count--
if count == 0 {
break
}
}
}
// traverse moves along the tree adding named params as it comes and across them.
// Returns the node and component found.
func (n *node) traverse(components []string, params url.Values) (*node, string) {
component := components[0]
if len(n.children) > 0 { // no children, then bail out.
for _, child := range n.children {
if component == child.component || child.isNamedParam {
if child.isNamedParam && params != nil {
params.Add(child.component[1:], component)
}
next := components[1:]
if len(next) > 0 { // http://xkcd.com/1270/
return child.traverse(next, params) // tail recursion is it's own reward.
}
return child, component
}
}
}
return n, component
}