-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
webhook.go
96 lines (80 loc) · 2.22 KB
/
webhook.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
package notify
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const webhookTimeOut = 5000 * time.Millisecond
// WebhookParams contain settings for webhook notifications
type WebhookParams struct {
Timeout time.Duration
Headers []string // headers in format "header:value"
}
// Webhook notifications client
type Webhook struct {
WebhookParams
webhookClient webhookClient
}
// webhookClient defines an interface of client for webhook
type webhookClient interface {
Do(*http.Request) (*http.Response, error)
}
// NewWebhook makes Webhook
func NewWebhook(params WebhookParams) *Webhook {
res := &Webhook{WebhookParams: params}
if res.Timeout == 0 {
res.Timeout = webhookTimeOut
}
res.webhookClient = &http.Client{Timeout: res.Timeout}
return res
}
// Send sends Webhook notification. Destination field is expected to have http:// or https:// schema.
//
// Example:
//
// - https://example.com/webhook
func (wh *Webhook) Send(ctx context.Context, destination, text string) error {
payload := bytes.NewBufferString(text)
httpReq, err := http.NewRequestWithContext(ctx, "POST", destination, payload)
if err != nil {
return fmt.Errorf("unable to create webhook request: %w", err)
}
for _, h := range wh.Headers {
elems := strings.Split(h, ":")
if len(elems) != 2 {
continue
}
httpReq.Header.Set(strings.TrimSpace(elems[0]), strings.TrimSpace(elems[1]))
}
resp, err := wh.webhookClient.Do(httpReq)
if err != nil {
return fmt.Errorf("webhook request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
errMsg := fmt.Sprintf("webhook request failed with non-OK status code: %d", resp.StatusCode)
respBody, e := io.ReadAll(resp.Body)
if e != nil {
return errors.New(errMsg)
}
return fmt.Errorf("%s, body: %s", errMsg, respBody)
}
return nil
}
// Schema returns schema prefix supported by this client
func (wh *Webhook) Schema() string {
return "http"
}
// String describes the webhook instance
func (wh *Webhook) String() string {
str := fmt.Sprintf("webhook notification with timeout %s", wh.Timeout)
if wh.Headers != nil {
str += fmt.Sprintf(" and headers %v", wh.Headers)
}
return str
}