0
0
mirror of https://github.com/thegeeklab/github-releases-notifier.git synced 2024-11-28 06:50:36 +00:00
github-releases-notifier/internal/handler/slack.go

67 lines
1.4 KiB
Go
Raw Normal View History

2020-09-21 07:15:27 +00:00
package handler
2017-08-08 10:08:16 +00:00
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
2020-09-21 07:15:27 +00:00
"github.com/thegeeklab/github-releases-notifier/internal/model"
2017-08-08 10:08:16 +00:00
)
// SlackSender has the hook to send slack notifications.
2017-08-08 10:08:16 +00:00
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.
2020-09-21 07:15:27 +00:00
func (s *SlackSender) Send(repository model.Repository) error {
2017-08-08 10:08:16 +00:00
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)
2017-08-08 10:08:16 +00:00
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
}