-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
68 lines (56 loc) · 1.6 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
68
package signup
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type slackService struct {
// Slack Incoming Webhook URL.
// https://hooks.slack.com/services/:workspaceID/:botID/:webhookID
// Can be found on the App's Incoming Webhooks page.
// https://api.slack.com/apps/A0338E8UFFV/incoming-webhooks?
webhookURL string
}
func (sl slackService) run(ctx context.Context, su Signup) error {
return sendWebhook(ctx, sl.webhookURL, message{Text: su.Summary()})
}
func (sl slackService) name() string {
return "slack service"
}
func NewSlackService(webhookURL string) *slackService {
return &slackService{
webhookURL: webhookURL,
}
}
// IsRequired returns false because the slack message notification is just nice to have.
func (sl slackService) isRequired() bool {
return false
}
type message struct {
Text string `json:"text"`
}
// SendWebhook POSTs a message to the OS Signups Slack App webhook.
// This incoming webhook posts a message to the #signups channel.
// https://api.slack.com/apps/A0338E8UFFV/incoming-webhooks
func sendWebhook(ctx context.Context, url string, msg message) error {
body, err := json.Marshal(msg)
if err != nil {
return fmt.Errorf("marshall: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(body))
if err != nil {
return fmt.Errorf("new request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("post request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return handleHTTPError(resp)
}
return nil
}