Created
March 12, 2020 09:28
-
-
Save matryer/09fc23c8c6ffccb146df072110ec1220 to your computer and use it in GitHub Desktop.
Post messages to Slack in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"io/ioutil" | |
"net/http" | |
"strings" | |
"time" | |
"github.com/pkg/errors" | |
) | |
type SlackMessage struct { | |
Blocks []SlackBlock `json:"blocks"` | |
} | |
type SlackText struct { | |
Type string `json:"type"` | |
Text string `json:"text"` | |
} | |
type SlackAccessory struct { | |
Type string `json:"type"` | |
Text *SlackText `json:"text,omitempty"` | |
URL string `json:"url,omitempty"` | |
Style string `json:"style,omitempty"` | |
ImageURL string `json:"image_url,omitempty"` | |
AltText string `json:"alt_text,omitempty"` | |
} | |
type SlackBlock struct { | |
Type string `json:"type"` | |
Text *SlackText `json:"text,omitempty"` | |
Elements []SlackText `json:"elements,omitempty"` | |
Accessory *SlackAccessory `json:"accessory,omitempty"` | |
} | |
func (m SlackMessage) Encode() (string, error) { | |
b, err := json.Marshal(m) | |
if err != nil { | |
return "", err | |
} | |
return string(b), nil | |
} | |
func (m SlackMessage) Post(ctx context.Context, WebhookURL string) error { | |
encoded, err := m.Encode() | |
if err != nil { | |
return err | |
} | |
client := &http.Client{ | |
Timeout: 2 * time.Second, | |
} | |
req, err := http.NewRequest(http.MethodPost, WebhookURL, strings.NewReader(encoded)) | |
if err != nil { | |
return err | |
} | |
req = req.WithContext(ctx) | |
req.Header.Set("Content-Type", "application/json") | |
resp, err := client.Do(req) | |
if err != nil { | |
return err | |
} | |
defer resp.Body.Close() | |
if resp.StatusCode != http.StatusOK { | |
bod, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
return errors.New("Not OK and couldn't read body") | |
} | |
return errors.New("Not OK: " + string(bod)) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment