forked from deoxxa/slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
64 lines (52 loc) · 1.48 KB
/
webhook.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
package slack
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
)
type Payload 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"`
Attachments []Attachment `json:"attachments",omitempty"`
}
type WebhookClient struct {
webhook_url string
timeout time.Duration
}
const DefaultTimeout = time.Duration(10 * time.Second)
// NewWebhookClient returns a Client with the provided webhook url (default timeout to 10 seconds)
func NewWebhookClient(webhook string, timeout time.Duration) *WebhookClient {
return &WebhookClient{webhook, timeout}
}
// SendMessage sends a text message to the default channel unless overridden
// https://api.slack.com/incoming-webhooks
func (c *WebhookClient) SendMessage(p *Payload) error {
if p == nil {
return errors.New("payload_missing")
}
client := http.Client{
Timeout: time.Duration(c.timeout),
}
body, err := json.Marshal(p)
if err != nil {
return err
}
res, err := client.Post(c.webhook_url, "application/json", bytes.NewBuffer(body))
if err != nil {
return err
}
defer res.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(res.Body)
s := buf.String() // Does a complete copy of the bytes in the buffer.
if s != "ok" {
return errors.New(s)
}
return nil
}