webhook.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package notifications
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/util"
  10. )
  11. type Webhook struct {
  12. Url string
  13. User string
  14. Password string
  15. Body string
  16. }
  17. var webhookQueue chan *Webhook
  18. var webhookLog log.Logger
  19. func initWebhookQueue() {
  20. webhookLog = log.New("notifications.webhook")
  21. webhookQueue = make(chan *Webhook, 10)
  22. go processWebhookQueue()
  23. }
  24. func processWebhookQueue() {
  25. for {
  26. select {
  27. case webhook := <-webhookQueue:
  28. err := sendWebRequest(webhook)
  29. if err != nil {
  30. webhookLog.Error("Failed to send webrequest ", "error", err)
  31. }
  32. }
  33. }
  34. }
  35. func sendWebRequest(webhook *Webhook) error {
  36. webhookLog.Debug("Sending webhook", "url", webhook.Url)
  37. client := http.Client{
  38. Timeout: time.Duration(3 * time.Second),
  39. }
  40. request, err := http.NewRequest("POST", webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  41. if webhook.User != "" && webhook.Password != "" {
  42. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  43. }
  44. if err != nil {
  45. return err
  46. }
  47. resp, err := client.Do(request)
  48. if err != nil {
  49. return err
  50. }
  51. _, err = ioutil.ReadAll(resp.Body)
  52. if err != nil {
  53. return err
  54. }
  55. if resp.StatusCode != 200 {
  56. return fmt.Errorf("Webhook response code %v", resp.StatusCode)
  57. }
  58. defer resp.Body.Close()
  59. return nil
  60. }
  61. var addToWebhookQueue = func(msg *Webhook) {
  62. webhookQueue <- msg
  63. }