-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathaction_mux.go
63 lines (54 loc) · 1.71 KB
/
action_mux.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 libonebot
import (
"fmt"
"sort"
)
// ActionMux 将动作请求按动作名称分发到不同的 Handler 对象处理.
type ActionMux struct {
handlers map[string]Handler
}
// NewActionMux 创建一个新的 ActionMux 对象.
func NewActionMux() *ActionMux {
mux := &ActionMux{
handlers: make(map[string]Handler),
}
mux.HandleFunc(ActionGetSupportedActions, mux.handleGetSupportedActions)
return mux
}
func (mux *ActionMux) handleGetSupportedActions(w ResponseWriter, r *Request) {
actions := make([]string, 0, len(mux.handlers))
for action := range mux.handlers {
actions = append(actions, action)
}
sort.Slice(actions, func(i, j int) bool {
return actions[i] < actions[j]
})
w.WriteData(actions)
}
// HandleAction 为 ActionMux 实现 Handler 接口.
func (mux *ActionMux) HandleAction(w ResponseWriter, r *Request) {
// return "ok" if otherwise explicitly set to "failed"
w.WriteOK()
handler := mux.handlers[r.Action]
if handler == nil {
err := fmt.Errorf("动作 `%v` 不存在", r.Action)
w.WriteFailed(RetCodeUnsupportedAction, err)
return
}
handler.HandleAction(w, r)
}
// HandleFunc 将一个函数注册为指定动作的请求处理器.
//
// 若要注册为核心动作的请求处理器, 建议使用 ActionXxx 常量作为动作名.
func (mux *ActionMux) HandleFunc(action string, handler func(ResponseWriter, *Request)) {
mux.Handle(action, HandlerFunc(handler))
}
// Handle 将一个 Handler 对象注册为指定动作的请求处理器.
//
// 若要注册为核心动作的请求处理器, 建议使用 ActionXxx 常量作为动作名.
func (mux *ActionMux) Handle(action string, handler Handler) {
if action == "" {
panic("动作名称不能为空")
}
mux.handlers[action] = handler
}