-
Notifications
You must be signed in to change notification settings - Fork 58
/
router.go
73 lines (64 loc) · 1.58 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
package dingtalk
import (
"encoding/json"
"io"
"net/http"
"strings"
)
var cmdTable = make(map[string]*command)
type command struct {
executor ExecFunc
isAdmin bool // 是否需要管理员权限
arity int // 参数个数
}
func RegisterCommand(name string, execFunc ExecFunc, arity int, isAdmin bool) {
cmdTable[name] = &command{
executor: execFunc,
arity: arity,
isAdmin: isAdmin,
}
}
func validateArity(arity int, cmdArgs []string) bool {
argNum := len(cmdArgs)
if arity >= 0 {
return argNum == arity
}
return argNum >= -arity
}
func execDingCommand(msg outGoingModel) []byte {
content := msg.Text.Content
keyAndArgs := strings.Split(strings.TrimSpace(content), " ")
cmdName := strings.ToLower(keyAndArgs[0])
cmd, ok := cmdTable[cmdName]
if !ok {
return NewTextMsg("ERR: unregistered command '" + cmdName + "'").Marshaler()
}
if !validateArity(cmd.arity, keyAndArgs) {
return NewTextMsg("ERR: wrong number of arguments for '" + cmdName + "' command").Marshaler()
}
if cmd.isAdmin && msg.IsAdmin != cmd.isAdmin {
return NewTextMsg("ERR '" + cmdName + "': you have no right to do this operation").Marshaler()
}
return cmd.executor(keyAndArgs[1:])
}
// MyHandler实现Handler接口
type OutGoingHandler struct{}
func (h *OutGoingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body := r.Body
var err error
var buf []byte
obj := outGoingModel{}
buf, err = io.ReadAll(body)
if err != nil {
return
}
err = json.Unmarshal(buf, &obj)
if err != nil {
return
}
msg := execDingCommand(obj)
if msg == nil {
return
}
_, _ = w.Write(msg)
}