webhook.go 1.2 KB

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