-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
70 lines (62 loc) · 1.44 KB
/
handlers.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
package main
import (
"bytes"
"encoding/json"
"github.com/bwmarrin/discordgo"
"github.com/julienschmidt/httprouter"
"io/ioutil"
"net/http"
"strconv"
)
type Response struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
}
func HandleInvokeHook(hook Hook) httprouter.Handle {
return func(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
body, err := ioutil.ReadAll(req.Body)
if err != nil {
// Connection closed prematurely.
return
}
_ = req.Body.Close()
hookParams, err := hook.Impl.Handle(req, body)
if err != nil {
body, err := json.Marshal(Response{false, err.Error()})
if err != nil {
panic(err)
}
rw.WriteHeader(http.StatusBadRequest)
_, _ = rw.Write(body)
return
}
if hookParams != nil {
body, err := json.Marshal(hookParams)
if err != nil {
panic(err)
}
for _, out := range hook.Invoke {
res, err := http.Post(
discordgo.EndpointWebhookToken(strconv.FormatInt(out.ID, 10), out.Token),
"application/json",
bytes.NewReader(body),
)
if err != nil {
body, err := json.Marshal(Response{false, err.Error()})
if err != nil {
panic(err)
}
rw.WriteHeader(res.StatusCode)
_, _ = rw.Write(body)
return
}
}
}
resp, err := json.Marshal(Response{true, ""})
if err != nil {
panic(err)
}
rw.Write(resp)
}
}