This repository was archived by the owner on Jul 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathslack.go
More file actions
67 lines (56 loc) · 1.35 KB
/
slack.go
File metadata and controls
67 lines (56 loc) · 1.35 KB
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type SlackPayload struct {
UnfurlLinks bool `json:"unfurl_links,omitempty"`
Username string `json:"username,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
IconURL string `json:"icon_url,omitempty"`
Channel string `json:"channel,omitempty"`
Text string `json:"text"`
}
type SlackClient struct {
webhook string
username string
httpClient http.Client
}
// NewSlackClient returns a Client with the provided webhook url (default timeout to 10 seconds)
func NewSlackClient(webhook, username string) *SlackClient {
httpClient := http.Client{
Timeout: 10 * time.Second,
}
c := &SlackClient{
webhook: webhook,
username: username,
httpClient: httpClient,
}
return c
}
// Send sends a text message to the default channel unless overridden
// https://api.slack.com/incoming-webhooks
func (c *SlackClient) Send(p SlackPayload) error {
p.Username = c.username
body, err := json.Marshal(p)
if err != nil {
return err
}
res, err := c.httpClient.Post(c.webhook, "application/json", bytes.NewBuffer(body))
if err != nil {
return err
}
defer res.Body.Close()
s, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
if string(s) != "ok" {
return fmt.Errorf("Slack error: %s", string(s))
}
return nil
}