webhook.go 2.0 KB

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