webhook.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package notifications
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "time"
  10. "golang.org/x/net/context/ctxhttp"
  11. "github.com/grafana/grafana/pkg/util"
  12. )
  13. type Webhook struct {
  14. Url string
  15. User string
  16. Password string
  17. Body string
  18. HttpMethod string
  19. HttpHeader map[string]string
  20. }
  21. var netTransport = &http.Transport{
  22. Proxy: http.ProxyFromEnvironment,
  23. Dial: (&net.Dialer{
  24. Timeout: 30 * time.Second,
  25. DualStack: true,
  26. }).Dial,
  27. TLSHandshakeTimeout: 5 * time.Second,
  28. }
  29. var netClient = &http.Client{
  30. Timeout: time.Second * 30,
  31. Transport: netTransport,
  32. }
  33. func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
  34. ns.log.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod)
  35. if webhook.HttpMethod == "" {
  36. webhook.HttpMethod = http.MethodPost
  37. }
  38. request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  39. if err != nil {
  40. return err
  41. }
  42. request.Header.Add("Content-Type", "application/json")
  43. request.Header.Add("User-Agent", "Grafana")
  44. if webhook.User != "" && webhook.Password != "" {
  45. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  46. }
  47. for k, v := range webhook.HttpHeader {
  48. request.Header.Set(k, v)
  49. }
  50. resp, err := ctxhttp.Do(ctx, netClient, request)
  51. if err != nil {
  52. return err
  53. }
  54. if resp.StatusCode/100 == 2 {
  55. return nil
  56. }
  57. defer resp.Body.Close()
  58. body, err := ioutil.ReadAll(resp.Body)
  59. if err != nil {
  60. return err
  61. }
  62. ns.log.Debug("Webhook failed", "statuscode", resp.Status, "body", string(body))
  63. return fmt.Errorf("Webhook response status %v", resp.Status)
  64. }