-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack.go
63 lines (54 loc) · 1.21 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
package main
import (
"bytes"
"fmt"
"net/http"
"time"
)
const DefaultSlackTimeout = 5 * time.Second
type SlackClient struct {
WebHookUrl string
UserName string
Channel string
Timeout time.Duration
}
func NewSlackClient(username string, adapter SSMAdapter) (SlackClient, error) {
webHookUrl, err := adapter.get(EnvKeyWebhookURL)
if err != nil {
return SlackClient{}, fmt.Errorf("can not get webHookUrl, %w", err)
}
return SlackClient{
WebHookUrl: webHookUrl,
UserName: username,
Timeout: DefaultSlackTimeout,
}, nil
}
func (sc SlackClient) sendHttpRequest(body string) error {
req, err := http.NewRequest(
http.MethodPost,
sc.WebHookUrl,
bytes.NewBuffer([]byte(body)),
)
if err != nil {
return fmt.Errorf("error with sendHttpRequest, %w", err)
}
req.Header.Add("Content-Type", "application/json")
if sc.Timeout == 0 {
sc.Timeout = DefaultSlackTimeout
}
client := &http.Client{Timeout: sc.Timeout}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var buf bytes.Buffer
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return err
}
if buf.String() != "ok" {
return fmt.Errorf("error returned from Slack, %s", buf.String())
}
return nil
}