forked from wpajqz/linker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
68 lines (54 loc) · 1.48 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
package linker
import (
"hash/crc32"
"strconv"
)
type (
Router struct {
prefix string
handlerContainer map[uint32]Handler
routerMiddleware map[uint32][]Middleware
middleware []Middleware
}
LinkRouter func(*Router)
)
func NewRouter() *Router {
return &Router{
handlerContainer: make(map[uint32]Handler),
routerMiddleware: make(map[uint32][]Middleware),
}
}
// 获取带命名空间router
func (r *Router) NSRouter(prefix string, params ...LinkRouter) *Router {
r.prefix = prefix
for _, p := range params {
p(r)
}
return r
}
// 命名空间路由注册路由和中间件
func (r *Router) NSRoute(pattern string, handler Handler, middleware ...Middleware) LinkRouter {
return func(r *Router) {
if r.prefix != "" {
pattern = r.prefix + pattern
}
r.Route(pattern, handler, middleware...)
}
}
// 注册路由,路由中间件
func (r *Router) Route(pattern string, handler Handler, middleware ...Middleware) *Router {
operator := crc32.ChecksumIEEE([]byte(pattern))
if operator <= OPERATOR_MAX {
panic("Unavailable operator, the value of crc32 need less than " + strconv.Itoa(OPERATOR_MAX))
}
r.routerMiddleware[operator] = append(r.routerMiddleware[operator], middleware...)
if _, ok := r.handlerContainer[operator]; !ok {
r.handlerContainer[operator] = handler
}
return r
}
// 添加请求需要进行处理的中间件
func (r *Router) Use(middleware ...Middleware) *Router {
r.middleware = append(r.middleware, middleware...)
return r
}