webhook.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. ContentType string
  21. }
  22. var netTransport = &http.Transport{
  23. Proxy: http.ProxyFromEnvironment,
  24. Dial: (&net.Dialer{
  25. Timeout: 30 * time.Second,
  26. DualStack: true,
  27. }).Dial,
  28. TLSHandshakeTimeout: 5 * time.Second,
  29. }
  30. var netClient = &http.Client{
  31. Timeout: time.Second * 30,
  32. Transport: netTransport,
  33. }
  34. func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *Webhook) error {
  35. ns.log.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod)
  36. if webhook.HttpMethod == "" {
  37. webhook.HttpMethod = http.MethodPost
  38. }
  39. request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  40. if err != nil {
  41. return err
  42. }
  43. if webhook.ContentType == "" {
  44. webhook.ContentType = "application/json"
  45. }
  46. request.Header.Add("Content-Type", webhook.ContentType)
  47. request.Header.Add("User-Agent", "Grafana")
  48. if webhook.User != "" && webhook.Password != "" {
  49. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  50. }
  51. for k, v := range webhook.HttpHeader {
  52. request.Header.Set(k, v)
  53. }
  54. resp, err := ctxhttp.Do(ctx, netClient, request)
  55. if err != nil {
  56. return err
  57. }
  58. if resp.StatusCode/100 == 2 {
  59. return nil
  60. }
  61. defer resp.Body.Close()
  62. body, err := ioutil.ReadAll(resp.Body)
  63. if err != nil {
  64. return err
  65. }
  66. ns.log.Debug("Webhook failed", "statuscode", resp.Status, "body", string(body))
  67. return fmt.Errorf("Webhook response status %v", resp.Status)
  68. }