-
Notifications
You must be signed in to change notification settings - Fork 1
/
slack.go
52 lines (45 loc) · 1.14 KB
/
slack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
func reportToSlack(slackHook string, report Report) error {
var message strings.Builder
message.WriteString("Listing undeletable resources")
if clusterType := os.Getenv("CLUSTER_TYPE"); clusterType != "" {
message.WriteString(" for cluster " + clusterType)
}
message.WriteRune('\n')
for _, resource := range report.FailedToDelete {
message.WriteString(fmt.Sprintf("%s: %q\n", resource.Type(), resource.ID()))
}
var msg bytes.Buffer
if err := json.NewEncoder(&msg).Encode(struct {
Text string `json:"text"`
}{
Text: message.String(),
}); err != nil {
return fmt.Errorf("failed to build the JSON payload for Slack: %w", err)
}
res, err := http.Post(
slackHook,
"application/json",
&msg,
)
if err != nil {
return fmt.Errorf("failed to send a message to Slack: %w", err)
}
io.Copy(io.Discard, res.Body)
res.Body.Close()
switch res.StatusCode {
case http.StatusOK, http.StatusNoContent, http.StatusAccepted:
default:
return fmt.Errorf("unexpected status code %q while sending a Slack notification", res.Status)
}
return nil
}