webhook.go 2.0 KB

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