-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
66 lines (55 loc) · 1.06 KB
/
router.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
package jago
import (
"strings"
)
type (
Router struct {
routes *Trie
}
)
func newRouter() *Router {
r := &Router{
routes: newTrie(),
}
return r
}
func (r *Router) add(method, path string, handlers ...HandlerFunc) {
r.routes.add(method, path, handlers...)
}
func (r *Router) PrintTree() {
r.routes.printTree()
}
func (r *Router) find(uri string, method string, c Context) {
ctx := c.(*context)
uri = strings.TrimSuffix(uri, "/")
pathParts := getURIPaths(uri)
maxScore, n := r.routes.find(uri, method)
if maxScore > 0 {
ctx.pnames = n.getPathParam(pathParts)
ctx.handlers = n.handlers[method]
ctx.path = n.path
} else {
ctx.handlers = append(ctx.handlers, NotFoundHandler)
}
}
func getURIPaths(url string) []string {
paths := strings.Split(url, "/")
return filter(paths, func(v string) bool {
return v != ""
})
}
func filter(vs []string, f func(string) bool) []string {
vsf := make([]string, 0)
for _, v := range vs {
if f(v) {
vsf = append(vsf, v)
}
}
return vsf
}
func max(x, y int) int {
if x < y {
return y
}
return x
}