forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
84 lines (68 loc) · 1.77 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
package notifications
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
"golang.org/x/net/context/ctxhttp"
"github.com/grafana/grafana/pkg/util"
)
type Webhook struct {
Url string
User string
Password string
Body string
HttpMethod string
HttpHeader map[string]string
ContentType string
}
var netTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
DualStack: true,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
var netClient = &http.Client{
Timeout: time.Second * 30,
Transport: netTransport,
}
func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
ns.log.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod)
if webhook.HttpMethod == "" {
webhook.HttpMethod = http.MethodPost
}
request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
if err != nil {
return err
}
if webhook.ContentType == "" {
webhook.ContentType = "application/json"
}
request.Header.Add("Content-Type", webhook.ContentType)
request.Header.Add("User-Agent", "Grafana")
if webhook.User != "" && webhook.Password != "" {
request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
}
for k, v := range webhook.HttpHeader {
request.Header.Set(k, v)
}
resp, err := ctxhttp.Do(ctx, netClient, request)
if err != nil {
return err
}
if resp.StatusCode/100 == 2 {
return nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
ns.log.Debug("Webhook failed", "statuscode", resp.Status, "body", string(body))
return fmt.Errorf("Webhook response status %v", resp.Status)
}