-
Notifications
You must be signed in to change notification settings - Fork 1
/
webhook.go
61 lines (46 loc) · 1.17 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
package notifier
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const contentType = "application/json"
// WebhookNotifier sends notifications to webhook
type WebhookNotifier struct {
webhookURL string
}
// NewWebhookNotifier creates new webhook notifier
func NewWebhookNotifier(webhookURL string) WebhookNotifier {
return WebhookNotifier{
webhookURL: webhookURL,
}
}
// Notify convers payload to a readable message
// and sends it to webhook webhook url
func (sn WebhookNotifier) Notify(payload Payload) error {
reader, err := sn.toReader(payload)
if err != nil {
return err
}
resp, err := http.Post(sn.webhookURL, contentType, reader)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Failed to send notification to webhook, status %d", resp.StatusCode)
}
return nil
}
func (sn WebhookNotifier) toReader(payload Payload) (io.Reader, error) {
text := fmt.Sprintf("%s %s/%s - %s", payload.Kind, payload.Namespace, payload.Name, payload.Error)
var body = map[string]string{
"text": text,
}
rawBody, err := json.Marshal(body)
if err != nil {
return nil, err
}
return bytes.NewBuffer(rawBody), nil
}