-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
95 lines (80 loc) · 1.91 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
package uim
import (
"fmt"
"sync"
"github.com/uim/wire/pkt"
)
type Router struct {
middlewares []HandlerFunc
handlers *FuncTree
pool sync.Pool
}
func NewRouter() *Router {
r := &Router{
handlers: NewTree(),
middlewares: make([]HandlerFunc, 0),
}
r.pool.New = func() interface{} {
return BuildContext()
}
return r
}
func (r *Router) Use(handlers ...HandlerFunc) {
r.middlewares = append(r.middlewares, handlers...)
}
// Handle register a command handler.
func (r *Router) Handle(command string, handlers ...HandlerFunc) {
r.handlers.Add(command, r.middlewares...)
r.handlers.Add(command, handlers...)
}
// Serve a packet from client.
func (r *Router) Serve(packet *pkt.LogicPkt, dispatcher Dispatcher, cache SessionStorage, session Session) error {
if dispatcher == nil {
return fmt.Errorf("dispatcher is nil")
}
if cache == nil {
return fmt.Errorf("cache is nil")
}
ctx := r.pool.Get().(*ContextImpl)
ctx.reset()
ctx.request = packet
ctx.Dispatcher = dispatcher
ctx.SessionStorage = cache
ctx.session = session
r.serveContext(ctx)
r.pool.Put(ctx)
return nil
}
func (r *Router) serveContext(ctx *ContextImpl) {
chain, ok := r.handlers.Get(ctx.Header().Command)
if !ok {
ctx.handlers = []HandlerFunc{handleNoFound}
ctx.Next()
return
}
ctx.handlers = chain
ctx.Next()
}
func handleNoFound(ctx Context) {
_ = ctx.Resp(pkt.Status_NotImplemented, &pkt.ErrorResp{Message: "NotImplemented"})
}
type FuncTree struct {
nodes map[string]HandlersChain
}
func NewTree() *FuncTree {
return &FuncTree{
nodes: make(map[string]HandlersChain, 10),
}
}
// Add a handler to tree.
func (t *FuncTree) Add(path string, handlers ...HandlerFunc) {
if t.nodes[path] == nil {
t.nodes[path] = HandlersChain{}
}
t.nodes[path] = append(t.nodes[path], handlers...)
}
// get a handler from tree.
func (t *FuncTree) Get(path string) (HandlersChain, bool) {
f, ok := t.nodes[path]
return f, ok
}