-
Notifications
You must be signed in to change notification settings - Fork 218
/
http.go
281 lines (237 loc) · 8.58 KB
/
http.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package http
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/nikoksr/notify"
)
type (
// PreSendHookFn defines a function signature for a pre-send hook.
PreSendHookFn func(req *http.Request) error
// PostSendHookFn defines a function signature for a post-send hook.
PostSendHookFn func(req *http.Request, resp *http.Response) error
// BuildPayloadFn defines a function signature for a function that builds a payload.
BuildPayloadFn func(subject, message string) (payload any)
// Serializer is used to serialize the payload to a byte slice.
Serializer interface {
Marshal(contentType string, payload any) (payloadRaw []byte, err error)
}
// Webhook represents a single webhook receiver. It contains all the information needed to send a valid request to
// the receiver. The BuildPayload function is used to build the payload that will be sent to the receiver from the
// given subject and message.
Webhook struct {
ContentType string
Header http.Header
Method string
URL string
BuildPayload BuildPayloadFn
}
// Service is the main struct of this package. It contains all the information needed to send notifications to a
// list of receivers. The receivers are represented by Webhooks and are expected to be valid HTTP endpoints. The
// Service also allows.
Service struct {
client *http.Client
webhooks []*Webhook
preSendHooks []PreSendHookFn
postSendHooks []PostSendHookFn
Serializer Serializer
}
)
const (
defaultUserAgent = "notify/" + notify.Version
defaultContentType = "application/json; charset=utf-8"
defaultRequestMethod = http.MethodPost
// Defining these as constants for testing purposes.
defaultSubjectKey = "subject"
defaultMessageKey = "message"
)
type defaultMarshaller struct{}
// Marshal takes a payload and serializes it to a byte slice. The content type is used to determine the serialization
// format. If the content type is not supported, an error is returned. The default marshaller supports the following
// content types: application/json, text/plain.
// NOTE: should we expand the default marshaller to support more content types?
func (defaultMarshaller) Marshal(contentType string, payload any) ([]byte, error) {
var out []byte
var err error
switch {
case strings.HasPrefix(contentType, "application/json"):
out, err = json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("marshal payload: %w", err)
}
case strings.HasPrefix(contentType, "text/plain"):
str, ok := payload.(string)
if !ok {
return nil, fmt.Errorf("payload was expected to be of type string, got %T", payload)
}
out = []byte(str)
default:
return nil, errors.New("unsupported content type")
}
return out, nil
}
// buildDefaultPayload is the default payload builder. It builds a payload that is a map with the keys "subject" and
// "message".
func buildDefaultPayload(subject, message string) any {
return map[string]string{
defaultSubjectKey: subject,
defaultMessageKey: message,
}
}
// New returns a new instance of a Service notification service. Parameter 'tag' is used as a log prefix and may be left
// empty, it has a fallback value.
func New() *Service {
return &Service{
client: http.DefaultClient,
webhooks: []*Webhook{},
preSendHooks: []PreSendHookFn{},
postSendHooks: []PostSendHookFn{},
Serializer: defaultMarshaller{},
}
}
func newWebhook(url string) *Webhook {
return &Webhook{
ContentType: defaultContentType,
Header: http.Header{},
Method: defaultRequestMethod,
URL: url,
BuildPayload: buildDefaultPayload,
}
}
// String returns a string representation of the webhook. It implements the fmt.Stringer interface.
func (w *Webhook) String() string {
if w == nil {
return ""
}
return strings.TrimSpace(fmt.Sprintf("%s %s %s", strings.ToUpper(w.Method), w.URL, w.ContentType))
}
// AddReceivers accepts a list of Webhooks and adds them as receivers. The Webhooks are expected to be valid HTTP
// endpoints.
func (s *Service) AddReceivers(webhooks ...*Webhook) {
s.webhooks = append(s.webhooks, webhooks...)
}
// AddReceiversURLs accepts a list of URLs and adds them as receivers. Internally it converts the URLs to Webhooks by
// using the default content-type ("application/json") and request method ("POST").
func (s *Service) AddReceiversURLs(urls ...string) {
for _, url := range urls {
s.AddReceivers(newWebhook(url))
}
}
// WithClient sets the http client to be used for sending requests. Calling this method is optional, the default client
// will be used if this method is not called.
func (s *Service) WithClient(client *http.Client) {
if client != nil {
s.client = client
}
}
// doPreSendHooks executes all the pre-send hooks. If any of the hooks returns an error, the execution is stopped and
// the error is returned.
func (s *Service) doPreSendHooks(req *http.Request) error {
for _, hook := range s.preSendHooks {
if err := hook(req); err != nil {
return err
}
}
return nil
}
// doPostSendHooks executes all the post-send hooks. If any of the hooks returns an error, the execution is stopped and
// the error is returned.
func (s *Service) doPostSendHooks(req *http.Request, resp *http.Response) error {
for _, hook := range s.postSendHooks {
if err := hook(req, resp); err != nil {
return err
}
}
return nil
}
// PreSend adds a pre-send hook to the service. The hook will be executed before sending a request to a receiver.
func (s *Service) PreSend(hook PreSendHookFn) {
s.preSendHooks = append(s.preSendHooks, hook)
}
// PostSend adds a post-send hook to the service. The hook will be executed after sending a request to a receiver.
func (s *Service) PostSend(hook PostSendHookFn) {
s.postSendHooks = append(s.postSendHooks, hook)
}
// newRequest creates a new http request with the given method, content-type, url and payload. Request created by this
// function will usually be passed to the Service.do method.
func newRequest(ctx context.Context, hook *Webhook, payload io.Reader) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, hook.Method, hook.URL, payload)
if err != nil {
return nil, err
}
req.Header = hook.Header
if req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", defaultUserAgent)
}
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", hook.ContentType)
}
return req, nil
}
// do sends the given request and returns an error if the request failed. A failed request gets identified by either
// an unsuccessful status code or a non-nil error. The given request is expected to be valid and was usually created
// by the newRequest function.
func (s *Service) do(req *http.Request) error {
// Execute all pre-send hooks in order.
if err := s.doPreSendHooks(req); err != nil {
return fmt.Errorf("pre-send hooks: %w", err)
}
// Actually send the HTTP request.
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
// Execute all post-send hooks in order.
if err = s.doPostSendHooks(req, resp); err != nil {
return fmt.Errorf("post-send hooks: %w", err)
}
// Check if response code is 2xx. Should this be configurable?
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("responded with status code: %d", resp.StatusCode)
}
return nil
}
// send is a helper method that sends a message to a single webhook. It wraps the core logic of the Send method, which
// is creating a new request for the given webhook and sending it.
func (s *Service) send(ctx context.Context, webhook *Webhook, payload []byte) error {
// Create a new HTTP request for the given webhook.
req, err := newRequest(ctx, webhook, bytes.NewReader(payload))
if err != nil {
return fmt.Errorf("create request: %w", err)
}
defer func() { _ = req.Body.Close() }()
return s.do(req)
}
// Send takes a message and sends it to all webhooks.
func (s *Service) Send(ctx context.Context, subject, message string) error {
// Send message to all webhooks.
for _, webhook := range s.webhooks {
select {
case <-ctx.Done():
return ctx.Err()
default:
// Skip webhook if it is nil.
if webhook == nil {
continue
}
// Build the payload for the current webhook.
payload := webhook.BuildPayload(subject, message)
// Marshal the message into a payload.
payloadRaw, err := s.Serializer.Marshal(webhook.ContentType, payload)
if err != nil {
return fmt.Errorf("marshal payload: %w", err)
}
// Send the payload to the webhook.
if err = s.send(ctx, webhook, payloadRaw); err != nil {
return fmt.Errorf("send to %s: %w", webhook.URL, err)
}
}
}
return nil
}