-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
81 lines (73 loc) · 2.19 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"bytes"
"encoding/json"
"github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
)
type SlackField struct {
Text string `json:"value,omitempty"`
Title string `json:"title,omitempty"`
Short bool `json:"short,omitempty"`
}
type SlackAttachments struct {
Color string `json:"color,omitempty"`
Text string `json:"text,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Fields []SlackField `json:"fields,omitempty"`
Footer string `json:"footer,omitempty"`
FooterIcon string `json:"footer_icon,omitempty"`
Head string `json:"author_name,omitempty"`
}
type SlackMessage struct {
Text string `json:"text,omitempty"`
Attachments []SlackAttachments `json:"attachments,omitempty"`
}
func send_with_slack(msg Message, cfg Config) {
var body SlackMessage
var attachement SlackAttachments
attachement.Head = msg.Head
attachement.Text = msg.Body
if msg.Color != "" {
attachement.Color = msg.Color
}
if msg.Body_title != "" {
attachement.Title = msg.Body_title
}
if msg.Body_link != "" {
attachement.TitleLink = msg.Body_link
}
var fields []SlackField
for _, value := range msg.Fields {
var field SlackField
field.Title = value.Header
field.Text = value.Text
field.Short = value.Short
fields = append(fields, field)
}
attachement.Fields = fields
attachement.Footer = msg.Frontend + " (sendmsg " + gitversion + ")"
if msg.FrontendIconURL != "" {
attachement.FooterIcon = msg.FrontendIconURL
}
body.Attachments = []SlackAttachments{attachement}
jsonBody, err := json.Marshal(body)
if err != nil {
logrus.WithError(err).Fatal("Couldn't marshal message for JSON transport!")
}
resp, err := http.Post(cfg.Webhook, "application/reader", bytes.NewBuffer(jsonBody))
if err != nil {
logrus.WithError(err).Fatal("Couldn't POST message to webhook!")
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
logrus.WithError(err).Warnf("Couldn't read back response body!")
}
bodyString := string(bodyBytes)
if bodyString != "ok" {
logrus.WithField("rc", bodyString).Warnf("Slack didn't return 'OK'")
}
}