This repository was archived by the owner on Feb 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvolta_messaging.go
More file actions
266 lines (224 loc) · 6.13 KB
/
volta_messaging.go
File metadata and controls
266 lines (224 loc) · 6.13 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package volta
import (
"context"
"encoding/xml"
"math/rand"
"time"
"github.com/rabbitmq/amqp091-go"
)
func (a *App) AddConsumer(routingKey string, handlers ...Handler) {
a.mutex.Lock()
defer a.mutex.Unlock()
if a.handlers == nil {
a.handlers = make(map[string][]Handler)
}
a.handlers[routingKey] = handlers
}
// JSONConsumer is a helper function that creates a handler that will unmarshal the request body to the given type.
func JSONConsumer[Data any](callback func(ctx *Ctx, body Data) error) Handler {
return func(ctx *Ctx) error {
var body Data
if err := ctx.BindJSON(&body); err != nil {
return ctx.App.onBindError(ctx, err)
}
return callback(ctx, body)
}
}
// XMLConsumer is a helper function that creates a handler that will unmarshal the request body to the given type.
func XMLConsumer[Data any](callback func(ctx *Ctx, body Data) error) Handler {
return func(ctx *Ctx) error {
var body Data
if err := ctx.BindXML(&body); err != nil {
return ctx.App.onBindError(ctx, err)
}
return callback(ctx, body)
}
}
// Consume consumes messages from the queue with the given routing key.
// Handlers are the functions that will be executed when a message is received.
// Handlers are executed in the order they are passed.
func (a *App) consume(routingKey string, handlers ...Handler) error {
connection, err := amqp091.Dial(a.config.RabbitMQ)
if err != nil {
return err
}
channel, err := connection.Channel()
if err != nil {
return err
}
messages, err := channel.Consume(routingKey, randomString(12), false, false, false, false, nil)
if err != nil {
return err
}
handlersWithMiddlewares := make([]Handler, 0)
handlersWithMiddlewares = append(handlersWithMiddlewares, a.middlewares...)
handlersWithMiddlewares = append(handlersWithMiddlewares, handlers...)
go func() {
for message := range messages {
go func(msg amqp091.Delivery, h []Handler, channel *amqp091.Channel) {
h[0](&Ctx{App: a, Delivery: msg, handlers: h, Channel: channel})
}(message, handlersWithMiddlewares, channel)
}
defer connection.Close()
defer channel.Close()
}()
return nil
}
// ConsumeNative consumes messages from the specified routing key using the AMQP 0.9.1 protocol.
// It returns a channel of message deliveries and an error if any occurred.
func (a *App) ConsumeNative(routingKey string) (<-chan amqp091.Delivery, error) {
connection, err := amqp091.Dial(a.config.RabbitMQ)
if err != nil {
return nil, err
}
channel, err := connection.Channel()
if err != nil {
return nil, err
}
messages, err := channel.Consume(routingKey, randomString(12), false, false, false, false, nil)
if err != nil {
return nil, err
}
return messages, nil
}
func randomString(length int) string {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, length)
for i := range result {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
// Publish publishes a message to the exchange with the given name, body is the message body
// and exchange is the exchange name.
// No wait for response.
// Returns error if something went wrong.
func (a *App) Publish(name, exchange string, body []byte) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.config.Timeout)*time.Second)
defer cancel()
connection, err := amqp091.Dial(a.config.RabbitMQ)
if err != nil {
return err
}
defer connection.Close()
channel, err := connection.Channel()
if err != nil {
return err
}
defer channel.Close()
return channel.PublishWithContext(
ctx,
exchange,
name,
false,
false,
amqp091.Publishing{
ContentType: "text/plain",
Body: body,
})
}
// Request publishes a message to the exchange with the given name, body is the message body
// and exchange is the exchange name.
// Waits for response.
func (a *App) Request(name, exchange string, body []byte) (data []byte, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.config.Timeout)*time.Second)
defer cancel()
connection, err := amqp091.Dial(a.config.RabbitMQ)
if err != nil {
return nil, err
}
defer connection.Close()
channel, err := connection.Channel()
if err != nil {
return nil, err
}
defer channel.Close()
queue, err := channel.QueueDeclare(
"",
false,
false,
true,
false,
nil,
)
if err != nil {
return nil, err
}
corrId := randomString(32)
err = channel.PublishWithContext(
ctx,
exchange,
name,
false,
false,
amqp091.Publishing{
ContentType: "text/plain",
CorrelationId: corrId,
ReplyTo: queue.Name,
Body: body,
})
if err != nil {
return nil, err
}
messages, err := channel.Consume(
queue.Name,
"",
true,
false,
true,
false,
nil,
)
if err != nil {
return nil, err
}
for message := range messages {
if message.CorrelationId == corrId {
return message.Body, nil
}
}
return nil, nil
}
// PublishJSON publishes a message to the exchange with the given name, body will be marshaled to JSON
// and exchange is the exchange name.
// No wait for response.
func (a *App) PublishJSON(name, exchange string, body interface{}) error {
data, err := a.config.Marshal(body)
if err != nil {
return err
}
return a.Publish(name, exchange, data)
}
// RequestJSON publishes a message to the exchange with the given name, body will be marshaled to JSON
// and exchange is the exchange name.
// Waits for response.
// Unmarshals response to response interface.
func (a *App) RequestJSON(name, exchange string, body interface{}, response interface{}) error {
data, err := a.config.Marshal(body)
if err != nil {
return err
}
resp, err := a.Request(name, exchange, data)
if err != nil {
return err
}
return a.config.Unmarshal(resp, &response)
}
func (a *App) PublishXML(name, exchange string, body interface{}) error {
data, err := xml.Marshal(body)
if err != nil {
return err
}
return a.Publish(name, exchange, data)
}
func (a *App) RequestXML(name, exchange string, body interface{}, response interface{}) error {
data, err := xml.Marshal(body)
if err != nil {
return err
}
resp, err := a.Request(name, exchange, data)
if err != nil {
return err
}
return xml.Unmarshal(resp, &response)
}