CLI to run health checks against sensor stations on openSenseMap.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.6KB

  1. package core
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "github.com/dghubble/sling"
  7. "github.com/spf13/viper"
  8. )
  9. var slackClient = sling.New().Client(&http.Client{})
  10. var notificationColors = map[string]string {
  11. CheckOk: "#00ff00",
  12. CheckErr: "#ff0000",
  13. }
  14. // slack Notifier has no configuration
  15. type SlackNotifier struct {
  16. webhook string
  17. }
  18. type SlackMessage struct {
  19. Text string `json:"text"`
  20. Username string `json:"username,omitempty`
  21. Attachments []SlackAttachment `json:"attachments,omitempty"`
  22. }
  23. type SlackAttachment struct {
  24. Text string `json:"text"`
  25. Color string `json:"color,omitempty"`
  26. }
  27. func (n SlackNotifier) New(config TransportConfig) (AbstractNotifier, error) {
  28. // validate transport configuration
  29. // :TransportConfSourceHack
  30. baseUrl := viper.GetString("slack.webhook")
  31. if baseUrl == "" {
  32. return nil, fmt.Errorf("Missing configuration key slack.webhook")
  33. }
  34. return SlackNotifier{
  35. webhook: baseUrl,
  36. }, nil
  37. }
  38. func (n SlackNotifier) Submit(notification Notification) error {
  39. message := &SlackMessage{
  40. Username: "osem_notify box healthcheck",
  41. Text: notification.Subject,
  42. Attachments: []SlackAttachment{ { notification.Body, notificationColors[notification.Status] } },
  43. }
  44. req, err := slackClient.Post(n.webhook).BodyJSON(message).Request()
  45. if err != nil {
  46. return err
  47. }
  48. c := http.Client{}
  49. res, err2 := c.Do(req)
  50. if err2 != nil {
  51. return err2
  52. }
  53. if res.StatusCode > 200 {
  54. defer res.Body.Close()
  55. body, _ := ioutil.ReadAll(res.Body)
  56. return fmt.Errorf("slack webhook failed: %s", body)
  57. }
  58. return nil
  59. }