allow several recipients allow custom per-target recipients, falling back to discord.webhooks drop sling dependency
70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package core
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var notificationColors = map[string]string{
|
|
CheckOk: "#00ff00",
|
|
CheckErr: "#ff0000",
|
|
}
|
|
|
|
type SlackNotifier struct {
|
|
NotifierOpts
|
|
}
|
|
|
|
type SlackMessage struct {
|
|
Text string `json:"text"`
|
|
Username string `json:"username,omitempty`
|
|
Attachments []SlackAttachment `json:"attachments,omitempty"`
|
|
}
|
|
|
|
type SlackAttachment struct {
|
|
Text string `json:"text"`
|
|
Color string `json:"color,omitempty"`
|
|
}
|
|
|
|
func (n SlackNotifier) New(config TransportConfig) (AbstractNotifier, error) {
|
|
if config.Options.Recipients == nil {
|
|
// fall back to global webhooks config :TransportConfSourceHack
|
|
webhooks := viper.GetStringSlice("slack.webhooks")
|
|
if len(webhooks) > 0 {
|
|
return SlackNotifier{NotifierOpts: NotifierOpts{Recipients: webhooks}}, nil
|
|
}
|
|
return nil, fmt.Errorf("Missing entries in config slack.webhooks")
|
|
}
|
|
return SlackNotifier{NotifierOpts: config.Options}, nil
|
|
}
|
|
|
|
func (n SlackNotifier) Submit(notification Notification) error {
|
|
msg, err := json.Marshal(SlackMessage{
|
|
Username: "statusmon",
|
|
Text: notification.Subject,
|
|
Attachments: []SlackAttachment{{notification.Body, notificationColors[notification.Status]}},
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
msgBuf := bytes.NewBuffer(msg)
|
|
|
|
for _, url := range n.Recipients {
|
|
res, err := http.Post(url, "application/json", msgBuf)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if res.StatusCode > 204 {
|
|
defer res.Body.Close()
|
|
body, _ := ioutil.ReadAll(res.Body)
|
|
return fmt.Errorf("slack webhook failed: %s", body)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|