-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
90 lines (83 loc) · 2.07 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
85
86
87
88
89
90
package axisapi
import (
"log"
"net/http"
"strings"
)
type router struct {
roots map[string]*node // 添加路由前缀树
handlers map[string]HandleFunc
}
func newRouter() *router {
return &router{
roots: make(map[string]*node),
handlers: make(map[string]HandleFunc),
}
}
// 以/分割路由,并且只允许*在最后
func parsePattern(pattern string) []string {
p := strings.Split(pattern, "/")
parts := make([]string, 0)
for _, item := range p {
if item != "" {
parts = append(parts, item)
// only allowed one '*'
if item[0] == '*' {
break
}
}
}
return parts
}
func (r *router) addRoute(method string, pattern string, handler HandleFunc) {
log.Printf("Router %4s - %s", method, pattern)
parts := parsePattern(pattern)
key := method + "|" + pattern
_, ok := r.roots[method]
if !ok {
r.roots[method] = &node{}
}
r.roots[method].insert(pattern, parts, 0)
r.handlers[key] = handler
}
func (r *router) getRouter(method string, path string) (*node, map[string]string) {
searchParts := parsePattern(path)
params := make(map[string]string)
root, ok := r.roots[method]
if !ok {
return nil, nil
}
n := root.search(searchParts, 0)
if n != nil {
parts := parsePattern(n.pattern)
// 获取动态路由中的参数如/a/:name - /a/boo --> name=boo
for index, part := range parts {
if part[0] == ':' {
params[part[1:]] = searchParts[index]
}
// *temp/a/b --> temp = /a/b
if part[0] == '*' && len(part) > 1 {
params[part[1:]] = strings.Join(searchParts[index:], "/")
break
}
}
return n, params
}
return nil, nil
}
func (r *router) handle(ctx *Context) {
// 设置中间件(所有handle function)
n, params := r.getRouter(ctx.Method, ctx.Path)
if n != nil {
ctx.Params = params
key := ctx.Method + "|" + n.pattern
// 处理函数(不是中间件)最后执行
ctx.handlers = append(ctx.handlers, r.handlers[key])
} else {
ctx.handlers = append(ctx.handlers, func(ctx *Context) {
ctx.String(http.StatusNotFound, "404 NOT FOUND: %s\n", ctx.Path)
})
}
// 执行所有handle function
ctx.Next()
}