forked from justwatchcom/github-releases-notifier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
slack.go
67 lines (58 loc) · 1.4 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
64
65
66
67
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/magmel48/github-releases-notifier/pkg/models"
"io/ioutil"
"net/http"
"time"
)
// SlackSender has the hook to send slack notifications.
type SlackSender struct {
Hook string
Username string
Icon string
}
type slackPayload struct {
Username string `json:"username"`
IconUrl string `json:"icon_url"`
Text string `json:"text"`
}
// Send a notification with a formatted message build from the repository.
func (s *SlackSender) Send(repository models.Repository) error {
payload := slackPayload{
Username: s.Username,
IconUrl: s.Icon,
Text: fmt.Sprintf(
"<%s|%s/%s>: <%s|%s> released",
repository.URL.String(),
repository.Owner,
repository.Name,
repository.Release.URL.String(),
repository.Release.Name,
),
}
payloadData, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, s.Hook, bytes.NewReader(payloadData))
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
req = req.WithContext(ctx)
defer cancel()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("request didn't respond with 200 OK: %s, %s", resp.Status, body)
}
return nil
}