-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
71 lines (63 loc) · 1.38 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
package web
import (
"fmt"
"net/http"
)
type router struct {
tree map[string]*trieTreeR
total int
}
func newRouter() *router {
return &router{
tree: make(map[string]*trieTreeR),
}
}
func parsePattern(pattern string) []string {
parts := make([]string, 0)
start := 0
for i := 0; i < len(pattern); i++ {
if pattern[i] == '/' && i == start {
start = i + 1
continue
}
if pattern[i] == '/' && i > start {
item := pattern[start:i]
parts = append(parts, item)
if item[0] == '*' {
break
}
start = i + 1
}
}
if start < len(pattern) {
parts = append(parts, pattern[start:])
}
return parts
}
func (r *router) addRoute(method string, pattern string, handler Handler) {
parts := parsePattern(pattern)
if _, has := r.tree[method]; !has {
r.tree[method] = newTrieTreeR()
}
r.total += r.tree[method].insert(parts, handler)
}
func (r *router) getRoute(method string, path string) (*nodeR, map[string]string) {
searchParts := parsePattern(path)
tree, ok := r.tree[method]
if !ok {
return nil, nil
}
return tree.search(searchParts)
}
func (r *router) handle(c *Context) {
n, params := r.getRoute(c.Method, c.Path)
if n != nil {
c.params = params
c.handlers = append(c.handlers, n.handler)
} else {
c.handlers = append(c.handlers, HandlerFunc(func(c *Context) {
c.Fail(http.StatusNotFound, fmt.Sprintf("404 NOT FOUND: %s", c.Path))
}))
}
c.Next()
}