/
adapter.go
61 lines (56 loc) · 1.1 KB
/
adapter.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
package slack
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
// Adapter ...
type Adapter struct {
cnf *Config
}
// NewAdapter starts a new Adapter instance
func NewAdapter(cnf *Config) *Adapter {
return &Adapter{
cnf: cnf,
}
}
// SendMessage pushes a message to one of Slack's channels
func (a *Adapter) SendMessage(channel, username, text, emoji string) error {
payload := map[string]string{
"text": text,
}
// All these are optional params, so don't send them if not set
if emoji != "" {
payload["icon_emoji"] = emoji
}
if channel != "" {
payload["channel"] = channel
}
if username != "" {
payload["username"] = username
}
payloadJSON, err := json.Marshal(payload)
if err != nil {
return err
}
resp, err := http.PostForm(
a.cnf.IncomingWebhook,
url.Values{
"payload": {string(payloadJSON)},
},
)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("Send Slack Message Error: %s", string(body))
}
return nil
}