-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.go
115 lines (95 loc) · 2.57 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package zoox
import (
"fmt"
"strings"
"github.com/go-zoox/core-utils/safe"
"github.com/go-zoox/logger"
"github.com/go-zoox/zoox/components/context/param"
route "github.com/go-zoox/zoox/components/router"
)
type router struct {
roots *safe.Map[string, any]
handlers *safe.Map[string, any]
}
func newRouter() *router {
return &router{
roots: safe.NewMap[string, any](),
handlers: safe.NewMap[string, any](),
}
}
func parsePath(path string) []string {
partsX := strings.Split(path, "/")
parts := []string{}
for _, part := range partsX {
if part != "" {
parts = append(parts, part)
// * is a wildcard
if part[0] == '*' {
break
}
}
}
return parts
}
func (r *router) addRoute(method string, path string, handler ...HandlerFunc) {
parts := parsePath(path)
key := fmt.Sprintf("%s %s", method, path)
if ok := r.roots.Has(method); !ok {
r.roots.Set(method, &route.Node{})
}
if r.handlers.Has(key) {
panic(fmt.Sprintf("[router] failed to register, route(%8s %s) has been already registered before", method, path))
}
logger.Info("[router] register: %8s %s", method, path)
r.roots.Get(method).(*route.Node).Insert(path, parts, 0)
r.handlers.Set(key, handler)
}
func (r *router) getRoute(method string, path string) (*route.Node, map[string]string) {
searchParts := parsePath(path)
if ok := r.roots.Has(method); !ok {
return nil, nil
}
root := r.roots.Get(method).(*route.Node)
if n := root.Search(searchParts, 0); n != nil {
params := make(map[string]string)
parts := parsePath(n.Path)
for i, part := range parts {
if part[0] == ':' {
// pattern: /user/:name
params[part[1:]] = searchParts[i]
} else if part[0] == '{' && part[len(part)-1] == '}' {
// pattern: /user/{name}
params[part[1:len(part)-1]] = searchParts[i]
} else if part[0] == '*' && len(part) > 1 {
// pattern: /file/*filepath
params[part[1:]] = strings.Join(searchParts[i:], "/")
break
}
}
return n, params
}
return nil, nil
}
func (r *router) handle(ctx *Context) {
n, params := r.getRoute(ctx.Method, ctx.Path)
if n != nil {
ctx.param = param.New(params)
key := fmt.Sprintf("%s %s", ctx.Method, n.Path)
if ok := r.handlers.Has(key); ok {
handler, ok := r.handlers.Get(key).([]HandlerFunc)
if ok {
ctx.handlers = append(ctx.handlers, handler...)
} else {
ctx.handlers = append(ctx.handlers, ctx.App.notfound)
}
} else {
ctx.handlers = append(ctx.handlers, ctx.App.notfound)
}
} else {
ctx.handlers = append(ctx.handlers, ctx.App.notfound)
}
ctx.Next()
if !ctx.Writer.Written() {
ctx.Writer.Flush()
}
}