This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
forked from justwatchcom/github-releases-notifier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
slack.go
64 lines (55 loc) · 1.31 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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// SlackSender has the hook to send slack notifications.
type SlackSender struct {
Hook string
}
type slackPayload struct {
Username string `json:"username"`
IconEmoji string `json:"icon_emoji"`
Text string `json:"text"`
}
// Send a notification with a formatted message build from the repository.
func (s *SlackSender) Send(repository Repository) error {
payload := slackPayload{
Username: "GitHub Releases",
IconEmoji: ":github:",
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
}