forked from chanxuehong/wechat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
63 lines (50 loc) · 1.47 KB
/
handler.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
package core
type Handler interface {
ServeMsg(*Context)
}
// HandlerChain --------------------------------------------------------------------------------------------------------
const maxHandlerChainSize = 64
var _ Handler = (HandlerChain)(nil)
type HandlerChain []Handler
// ServeMsg 实现 Handler 接口
func (chain HandlerChain) ServeMsg(ctx *Context) {
ctx.handlers = chain
ctx.Next()
}
func (chain *HandlerChain) AppendHandlerFunc(handlers ...func(*Context)) {
if len(handlers) == 0 {
return
}
for _, h := range handlers {
if h == nil {
panic("handler can not be nil")
}
}
handlers2 := make(HandlerChain, len(handlers))
for i := 0; i < len(handlers); i++ {
handlers2[i] = HandlerFunc(handlers[i])
}
chain.AppendHandler(handlers2)
}
func (chain *HandlerChain) AppendHandler(handlers ...Handler) {
if len(handlers) == 0 {
return
}
for _, h := range handlers {
if h == nil {
panic("handler can not be nil")
}
}
*chain = combineHandlerChain(*chain, handlers)
}
func combineHandlerChain(middlewares, handlers HandlerChain) HandlerChain {
if len(middlewares)+len(handlers) > maxHandlerChainSize {
panic("too many handlers")
}
return append(middlewares, handlers...)
}
// HandlerFunc ---------------------------------------------------------------------------------------------------------
var _ Handler = HandlerFunc(nil)
type HandlerFunc func(*Context)
// ServeMsg 实现 Handler 接口
func (fn HandlerFunc) ServeMsg(ctx *Context) { fn(ctx) }