-
Notifications
You must be signed in to change notification settings - Fork 8
/
pusher.go
53 lines (48 loc) · 1.25 KB
/
pusher.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
log "github.com/sirupsen/logrus"
"github.com/tonkeeper/bridge/config"
)
type WebhookData struct {
Topic string `json:"topic"`
Hash string `json:"hash"`
}
func SendWebhook(clientID string, body WebhookData) {
if config.Config.WebhookURL == "" {
return
}
webhooks := strings.Split(config.Config.WebhookURL, ",")
for _, webhook := range webhooks {
go func(webhook string) {
err := sendWebhook(clientID, body, webhook)
if err != nil {
log.Errorf("failed to trigger webhook '%s': %v", webhook, err)
}
}(webhook)
}
}
func sendWebhook(clientID string, body WebhookData, webhook string) error {
postBody, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to marshal body: %w", err)
}
req, err := http.NewRequest(http.MethodPost, webhook+"/"+clientID, bytes.NewReader(postBody))
if err != nil {
return fmt.Errorf("failed to init request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed send request: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("bad status code: %v", res.StatusCode)
}
return nil
}