-
Notifications
You must be signed in to change notification settings - Fork 9
/
webhooks.go
117 lines (98 loc) · 2.43 KB
/
webhooks.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package blnk
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"github.com/sirupsen/logrus"
"github.com/jerry-enebeli/blnk/config"
"golang.org/x/net/context"
"github.com/hibiken/asynq"
)
type NewWebhook struct {
Event string `json:"event"`
Payload interface{} `json:"data"`
}
func processHTTP(data NewWebhook) error {
conf, err := config.Fetch()
if err != nil {
log.Println("Error fetching config:", err)
return err
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Println("Error marshaling data:", err)
return err
}
payload := bytes.NewBuffer(jsonData)
req, err := http.NewRequest("POST", conf.Notification.Webhook.Url, payload)
if err != nil {
log.Println("Error creating request:", err)
return err
}
for key, value := range conf.Notification.Webhook.Headers {
req.Header.Set(key, value)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error sending request:", err)
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
logrus.Error(err)
}
}(resp.Body)
// Check if the status code is not in the 2XX success range
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Printf("Request failed with status code: %d\n", resp.StatusCode)
return nil
}
var response map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
log.Println("Error decoding response:", err)
return err
}
log.Println("Webhook notification sent successfully:", response)
return nil
}
func SendWebhook(newWebhook NewWebhook) error {
conf, err := config.Fetch()
if err != nil {
return err
}
if conf.Notification.Webhook.Url == "" {
return nil
}
client := asynq.NewClient(asynq.RedisClientOpt{Addr: conf.Redis.Dns})
payload, err := json.Marshal(newWebhook)
if err != nil {
log.Fatal(err)
return err
}
taskOptions := []asynq.Option{asynq.Queue(WEBHOOK_QUEUE)}
task := asynq.NewTask(WEBHOOK_QUEUE, payload, taskOptions...)
info, err := client.Enqueue(task)
if err != nil {
log.Println(err, info)
return err
}
return err
}
func ProcessWebhook(_ context.Context, task *asynq.Task) error {
var payload NewWebhook
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
log.Printf("Error unmarshaling task payload: %v", err)
return err
}
log.Printf("Processing webhook: %+v\n", payload.Event)
err := processHTTP(payload)
if err != nil {
return err
}
return nil
}