webhook.go 1.9 KB

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