Debian Codegraph @

webhooks.go

raw symbols SCIP
1 package slack
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "io/ioutil"
10 "net/http"
11 )
12
13 type WebhookMessage struct {
14 Username string `json:"username,omitempty"`
15 IconEmoji string `json:"icon_emoji,omitempty"`
16 IconURL string `json:"icon_url,omitempty"`
17 Channel string `json:"channel,omitempty"`
18 ThreadTimestamp string `json:"thread_ts,omitempty"`
19 Text string `json:"text,omitempty"`
20 Attachments []Attachment `json:"attachments,omitempty"`
21 Parse string `json:"parse,omitempty"`
22 Blocks *Blocks `json:"blocks,omitempty"`
23 ResponseType string `json:"response_type,omitempty"`
24 ReplaceOriginal bool `json:"replace_original,omitempty"`
25 DeleteOriginal bool `json:"delete_original,omitempty"`
26 ReplyBroadcast bool `json:"reply_broadcast,omitempty"`
27 }
28
29 func PostWebhook(url string, msg *WebhookMessage) error {
30 return PostWebhookCustomHTTPContext(context.Background(), url, http.DefaultClient, msg)
31 }
32
33 func PostWebhookContext(ctx context.Context, url string, msg *WebhookMessage) error {
34 return PostWebhookCustomHTTPContext(ctx, url, http.DefaultClient, msg)
35 }
36
37 func PostWebhookCustomHTTP(url string, httpClient *http.Client, msg *WebhookMessage) error {
38 return PostWebhookCustomHTTPContext(context.Background(), url, httpClient, msg)
39 }
40
41 func PostWebhookCustomHTTPContext(ctx context.Context, url string, httpClient *http.Client, msg *WebhookMessage) error {
42 raw, err := json.Marshal(msg)
43 if err != nil {
44 return fmt.Errorf("marshal failed: %w", err)
45 }
46
47 req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(raw))
48 if err != nil {
49 return fmt.Errorf("failed new request: %w", err)
50 }
51 req.Header.Set("Content-Type", "application/json")
52
53 resp, err := httpClient.Do(req)
54 if err != nil {
55 return fmt.Errorf("failed to post webhook: %w", err)
56 }
57 defer func() {
58 io.Copy(ioutil.Discard, resp.Body)
59 resp.Body.Close()
60 }()
61
62 return checkStatusCode(resp, discard{})
63 }