-
Notifications
You must be signed in to change notification settings - Fork 36
/
server_impl.go
180 lines (147 loc) · 4.46 KB
/
server_impl.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package httpserver
import (
"bytes"
"context"
"encoding/hex"
"io"
"net/http"
"sync"
"time"
"github.com/disgoorg/disgo/json"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/log"
)
var _ Server = (*serverImpl)(nil)
// New creates a new Server with the given publicKey eventHandlerFunc and ConfigOpt(s)
func New(publicKey string, eventHandlerFunc EventHandlerFunc, opts ...ConfigOpt) Server {
config := DefaultConfig()
config.Apply(opts)
hexDecodedKey, err := hex.DecodeString(publicKey)
if err != nil {
config.Logger.Errorf("error while decoding hex string: %s", err)
}
return &serverImpl{
config: *config,
publicKey: hexDecodedKey,
eventHandlerFunc: eventHandlerFunc,
}
}
type serverImpl struct {
config Config
publicKey PublicKey
eventHandlerFunc EventHandlerFunc
}
func (s *serverImpl) Logger() log.Logger {
return s.config.Logger
}
func (s *serverImpl) PublicKey() PublicKey {
return s.publicKey
}
func (s *serverImpl) Handle(respondFunc RespondFunc, payload io.Reader) {
s.eventHandlerFunc(respondFunc, payload)
}
func (s *serverImpl) Start() {
s.config.ServeMux.Handle(s.config.URL, &WebhookInteractionHandler{server: s})
s.config.HTTPServer.Addr = s.config.Address
s.config.HTTPServer.Handler = s.config.ServeMux
go func() {
var err error
if s.config.CertFile != "" && s.config.KeyFile != "" {
err = s.config.HTTPServer.ListenAndServeTLS(s.config.CertFile, s.config.KeyFile)
} else {
err = s.config.HTTPServer.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
s.Logger().Error("error while running http server: ", err)
}
}()
}
func (s *serverImpl) Close(ctx context.Context) {
_ = s.config.HTTPServer.Shutdown(ctx)
}
// WebhookInteractionHandler implements the http.Handler interface and is used to handle interactions from Discord.
type WebhookInteractionHandler struct {
server Server
}
type replyStatus int
const (
replyStatusWaiting replyStatus = iota
replyStatusReplied
replyStatusTimedOut
)
func (h *WebhookInteractionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if ok := VerifyRequest(h.server.Logger(), r, h.server.PublicKey()); !ok {
w.WriteHeader(http.StatusUnauthorized)
data, _ := io.ReadAll(r.Body)
h.server.Logger().Trace("received http interaction with invalid signature. body: ", string(data))
return
}
defer func() {
_ = r.Body.Close()
}()
rqBody := &bytes.Buffer{}
rqData, _ := io.ReadAll(io.TeeReader(r.Body, rqBody))
h.server.Logger().Trace("received http interaction. body: ", string(rqData))
// these channels are used to communicate between the http handler and where the interaction is responded to
responseChannel := make(chan discord.InteractionResponse)
defer close(responseChannel)
errorChannel := make(chan error)
defer close(errorChannel)
// status of this interaction with a mutex to ensure usage between multiple goroutines
var (
status replyStatus
mu sync.Mutex
)
// send interaction to our handler
go h.server.Handle(func(response discord.InteractionResponse) error {
mu.Lock()
defer mu.Unlock()
if status == replyStatusTimedOut {
return discord.ErrInteractionExpired
}
if status == replyStatusReplied {
return discord.ErrInteractionAlreadyReplied
}
status = replyStatusReplied
responseChannel <- response
// wait if we get any error while processing the response
return <-errorChannel
}, rqBody)
var (
body any
err error
)
// wait for the interaction to be responded to or to time out after 3s
timer := time.NewTimer(time.Second * 3)
defer timer.Stop()
select {
case response := <-responseChannel:
if body, err = response.ToBody(); err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
errorChannel <- err
return
}
case <-timer.C:
mu.Lock()
defer mu.Unlock()
status = replyStatusTimedOut
h.server.Logger().Debug("interaction timed out")
http.Error(w, "interaction timed out", http.StatusRequestTimeout)
return
}
rsBody := &bytes.Buffer{}
multiWriter := io.MultiWriter(w, rsBody)
if multiPart, ok := body.(*discord.MultipartBuffer); ok {
w.Header().Set("Content-Type", multiPart.ContentType)
_, err = io.Copy(multiWriter, multiPart.Buffer)
} else {
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(multiWriter).Encode(body)
}
if err != nil {
errorChannel <- err
return
}
rsData, _ := io.ReadAll(rsBody)
h.server.Logger().Trace("response to http interaction. body: ", string(rsData))
}