forked from technosophos/slack-notify
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
108 lines (96 loc) · 2.57 KB
/
main.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
const (
EnvSlackWebhook = "SLACK_WEBHOOK"
EnvSlackIcon = "SLACK_ICON"
EnvSlackChannel = "SLACK_CHANNEL"
EnvSlackTitle = "SLACK_TITLE"
EnvSlackMessage = "SLACK_MESSAGE"
EnvSlackColor = "SLACK_COLOR"
EnvSlackUserName = "SLACK_USERNAME"
EnvSlackMarkdownSupport = "SLACK_MARKDOWN"
)
type Webhook struct {
Text string `json:"text,omitempty"`
UserName string `json:"username,omitempty"`
IconURL string `json:"icon_url,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
Channel string `json:"channel,omitempty"`
UnfurlLinks bool `json:"unfurl_links"`
Attachments []Attachment `json:"attachments,omitempty"`
MarkdownSupport bool `json:"mrkdwn,omitempty"`
}
type Attachment struct {
Fallback string `json:"fallback"`
Pretext string `json:"pretext,omitempty"`
Color string `json:"color,omitempty"`
Fields []Field `json:"fields,omitempty"`
}
type Field struct {
Title string `json:"title"`
Value string `json:"value,omitempty"`
Short bool `json:short"`
}
func main() {
endpoint := os.Getenv(EnvSlackWebhook)
if endpoint == "" {
fmt.Fprintln(os.Stderr, "URL is required")
os.Exit(1)
}
text := os.Getenv(EnvSlackMessage)
if text == "" {
fmt.Fprintln(os.Stderr, "Message is required")
os.Exit(1)
}
_, isMarkdownSupportEnabled := os.LookupEnv(EnvSlackMarkdownSupport)
msg := Webhook{
UserName: os.Getenv(EnvSlackUserName),
IconURL: os.Getenv(EnvSlackIcon),
Channel: os.Getenv(EnvSlackChannel),
MarkdownSupport: isMarkdownSupportEnabled,
Attachments: []Attachment{
{
Fallback: envOr(EnvSlackMessage, "This space intentionally left blank"),
Color: os.Getenv(EnvSlackColor),
Fields: []Field{
{
Title: os.Getenv(EnvSlackTitle),
Value: envOr(EnvSlackMessage, "EOM"),
},
},
},
},
}
if err := send(endpoint, msg); err != nil {
fmt.Fprintf(os.Stderr, "Error sending message: %s\n", err)
os.Exit(2)
}
}
func envOr(name, def string) string {
if d, ok := os.LookupEnv(name); ok {
return d
}
return def
}
func send(endpoint string, msg Webhook) error {
enc, err := json.Marshal(msg)
if err != nil {
return err
}
b := bytes.NewBuffer(enc)
res, err := http.Post(endpoint, "application/json", b)
if err != nil {
return err
}
if res.StatusCode >= 299 {
return fmt.Errorf("Error on message: %s\n", res.Status)
}
fmt.Println(res.Status)
return nil
}