-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathwebhooks.go
187 lines (166 loc) · 4.72 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blnk
import (
"bytes"
"context"
"encoding/json"
"io"
"log"
"net/http"
"strings"
"github.com/sirupsen/logrus"
"github.com/jerry-enebeli/blnk/config"
"github.com/hibiken/asynq"
)
// NewWebhook represents the structure of a webhook notification.
// It includes an event type and associated payload data.
type NewWebhook struct {
Event string `json:"event"` // The event type that triggered the webhook.
Payload interface{} `json:"data"` // The data associated with the event.
}
// getEventFromStatus maps a transaction status to a corresponding event string.
//
// Parameters:
// - status string: The status of the transaction.
//
// Returns:
// - string: The corresponding event string for the transaction status.
func getEventFromStatus(status string) string {
switch strings.ToLower(status) {
case strings.ToLower(StatusQueued):
return "transaction.queued"
case strings.ToLower(StatusApplied):
return "transaction.applied"
case strings.ToLower(StatusScheduled):
return "transaction.scheduled"
case strings.ToLower(StatusInflight):
return "transaction.inflight"
case strings.ToLower(StatusVoid):
return "transaction.void"
case strings.ToLower(StatusRejected):
return "transaction.rejected"
default:
return "transaction.unknown"
}
}
// processHTTP sends a webhook notification via HTTP POST request.
//
// Parameters:
// - data NewWebhook: The webhook notification data to send.
//
// Returns:
// - error: An error if the request or processing fails.
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
}
// SendWebhook enqueues a webhook notification task.
//
// Parameters:
// - newWebhook NewWebhook: The webhook notification data to enqueue.
//
// Returns:
// - error: An error if the task could not be enqueued.
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
}
// ProcessWebhook processes a webhook notification task from the queue.
//
// Parameters:
// - _ context.Context: The context for the operation.
// - task *asynq.Task: The task containing the webhook notification data.
//
// Returns:
// - error: An error if the webhook processing fails.
func ProcessWebhook(_ context.Context, task *asynq.Task) error {
conf, err := config.Fetch()
if err != nil {
return err
}
if conf.Notification.Webhook.Url == "" {
return nil
}
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
}