package notify import ( "context" "fmt" "log" "github.com/slack-go/slack" ) type SlackContextKey string const ( slackHookBaseURL = "hooks.slack.com/services" DryRunContextKey SlackContextKey = "dryRun" ) //Notifier interface represent mean to send notification type Notifier interface { Notify(message string) } //Message store and represent alerting message type Message struct { ShouldNotify bool Content string } type SlackNotifier struct { BotID string DestChannelID string WebhookID string } //NewSlackNotifier create slack notifier func NewSlackNotifier(BotID, DestChannelID, WebhookID string) *SlackNotifier { return &SlackNotifier{ BotID: BotID, DestChannelID: DestChannelID, WebhookID: WebhookID, } } //Notify send notification to channel func (sn *SlackNotifier) Notify(ctx context.Context, messages ...Message) { shouldNotify := false var content string for _, message := range messages { if message.ShouldNotify { shouldNotify = true content = fmt.Sprintf("%s\n%s", content, message.Content) } } if shouldNotify { msg := &slack.WebhookMessage{ Text: content, } url := fmt.Sprintf("https://%s/%s/%s/%s", slackHookBaseURL, sn.BotID, sn.DestChannelID, sn.WebhookID) if v := ctx.Value(DryRunContextKey); v != nil && v == true { log.Printf("dryrun mode : slack notify to %s\n", url) log.Printf("dryrun mode : %+v\n", msg) } else { err := slack.PostWebhook(url, msg) if err != nil { log.Printf("Send message error %+v", err) } } } }