forked from szpp-dev-team/slack-szppi-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
52 lines (43 loc) · 1.15 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
package main
import (
"encoding/json"
"log"
"net/http"
"strings"
"github.com/slack-go/slack"
)
type CommandExecutor interface {
Handle(slashCmd *slack.SlashCommand) error
Name() string
}
type SlashHandler struct {
client *slack.Client
executors []CommandExecutor
}
func NewSlashHandler(client *slack.Client) *SlashHandler {
return &SlashHandler{client, make([]CommandExecutor, 0, 100)}
}
func (s *SlashHandler) RegisterSubHandlers(executors ...CommandExecutor) {
s.executors = append(s.executors, executors...)
}
func (s *SlashHandler) Handle(rw http.ResponseWriter, slashCmd *slack.SlashCommand) {
tokens := strings.Fields(slashCmd.Text)
// TODO: show help if the length of tokens is 0
rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
// 打ったコマンドを表示させる
msg := &slack.Msg{ResponseType: slack.ResponseTypeInChannel}
_ = json.NewEncoder(rw).Encode(msg)
go func() {
subcommand := tokens[0]
for _, executor := range s.executors {
if executor.Name() == subcommand {
if err := executor.Handle(slashCmd); err != nil {
log.Println(err)
return
}
break
}
}
}()
}