webhook.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 ")
  29. }
  30. }
  31. }
  32. }
  33. func sendWebRequest(webhook *Webhook) error {
  34. webhookLog.Error("Sending stuff! ", "url", webhook.Url)
  35. client := http.Client{
  36. Timeout: time.Duration(3 * time.Second),
  37. }
  38. request, err := http.NewRequest("POST", webhook.Url, bytes.NewReader([]byte(webhook.Body)))
  39. if webhook.User != "" && webhook.Password != "" {
  40. request.Header.Add("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password))
  41. }
  42. if err != nil {
  43. return err
  44. }
  45. resp, err := client.Do(request)
  46. if err != nil {
  47. return err
  48. }
  49. defer resp.Body.Close()
  50. return nil
  51. }
  52. var addToWebhookQueue = func(msg *Webhook) {
  53. webhookQueue <- msg
  54. }