This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 143
/
webhook.go
95 lines (83 loc) · 2.4 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
package notifiers
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/argoproj-labs/argocd-notifications/shared/text"
)
type WebhookNotification struct {
Method string `json:"method"`
Body string `json:"body"`
Path string `json:"path"`
}
type Header struct {
Name string `json:"name"`
Value string `json:"value"`
}
type BasicAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}
type WebhookSettings struct {
Name string `json:"name"`
URL string `json:"url"`
Headers []Header `json:"headers"`
BasicAuth *BasicAuth `json:"basicAuth"`
}
// WebhookOptions holds list of configured webhooks settings
type WebhookOptions []WebhookSettings
func NewWebhookNotifier(opts WebhookOptions) Notifier {
return &webhookNotifier{opts: opts}
}
type webhookNotifier struct {
opts WebhookOptions
}
func findWebhookSettingsByName(settings []WebhookSettings, name string) (*WebhookSettings, error) {
for _, item := range settings {
if item.Name == name {
return &item, nil
}
}
return nil, fmt.Errorf("webhook with name '%s' is not configured", name)
}
func (w webhookNotifier) Send(notification Notification, recipient string) error {
webhookSettings, err := findWebhookSettingsByName(w.opts, recipient)
if err != nil {
return err
}
body := notification.Body
method := http.MethodGet
urlPath := ""
if webhookNotification, ok := notification.Webhook[webhookSettings.Name]; ok {
body = webhookNotification.Body
method = text.Coalesce(webhookNotification.Method, method)
if webhookNotification.Path != "" {
urlPath = webhookNotification.Path
}
}
url := strings.TrimRight(webhookSettings.URL, "/") + "/" + strings.TrimLeft(urlPath, "/")
req, err := http.NewRequest(method, url, bytes.NewBufferString(body))
if err != nil {
return err
}
for _, h := range webhookSettings.Headers {
req.Header.Set(h.Name, h.Value)
}
if webhookSettings.BasicAuth != nil {
req.SetBasicAuth(webhookSettings.BasicAuth.Username, webhookSettings.BasicAuth.Password)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if !(resp.StatusCode >= 200 && resp.StatusCode <= 299) {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
data = []byte(fmt.Sprintf("unable to read response data: %v", err))
}
return fmt.Errorf("request to %s has failed with error code %d : %s", url, resp.StatusCode, string(data))
}
return nil
}