aboutsummaryrefslogtreecommitdiff
path: root/webhook.go
blob: 897a24979768c16056f78cbaf78d7a941cefda3c (plain) (blame)
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
package checkup

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func SendDiscordAlert(hookURL string, message string) error {
	return SendWebhook(hookURL,
		struct {
			Content string `json:"content"`
		}{
			Content: message,
		}, http.StatusNoContent)

}

func SendRocketChatAlert(hookURL string, message string) error {
	return SendWebhook(hookURL,
		struct {
			Text string `json:"text"`
		}{
			Text: message,
		}, http.StatusOK)
}

func SendWebhook(hookURL string, msg interface{}, code int) error {
	buf := &bytes.Buffer{}
	enc := json.NewEncoder(buf)

	err := enc.Encode(msg)
	if err != nil {
		return err
	}

	resp, err := http.Post(hookURL, "application/json", buf)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != code {
		bod, err := ioutil.ReadAll(resp.Body)
		return fmt.Errorf("Bad status code: %d, expected %d : %s (Read errs: %s)",
			resp.StatusCode, http.StatusOK, bod, err)
	}

	return nil
}