-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
84 lines (60 loc) · 1.21 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package track
import (
"net/http"
)
type Router struct {
Children map[string]*Router
Value http.Handler
isEnd bool
isParam bool
Pram map[string]string
Method []string
middlewares []func(http.HandlerFunc) http.HandlerFunc
}
//New creates new instance
func New() *Router {
m := make(map[string]*Router)
params := make(map[string]string)
return &Router{Children: m, Pram: params}
}
func (r *Router) add(vals []string, method string, h http.Handler) {
if len(vals) < 1 {
r.isEnd = true
r.Value = h
r.Method = append(r.Method, method)
return
}
if _, ok := r.Children[vals[0]]; !ok {
r.Children[vals[0]] = New()
if vals[0][0] == ':' {
r.Children[vals[0]].isParam = true
}
}
r.Children[vals[0]].add(vals[1:], method, h)
}
func (r *Router) search(vals []string) *Router {
if r == nil {
return nil
}
curr := r
for _, v := range vals {
if _, ok := curr.Children[v]; !ok {
if len(curr.Children) > 0 {
for k := range curr.Children {
if curr.Children[k].isParam {
curr.Pram[k] = v
v = k
break
}
}
} else {
return nil
}
}
curr = curr.Children[v]
if curr == nil {
return nil
}
}
return curr
}