forked from asternic/wuzapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabbitmq.go
More file actions
100 lines (94 loc) · 2.35 KB
/
rabbitmq.go
File metadata and controls
100 lines (94 loc) · 2.35 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
package main
import (
"os"
"sync"
"github.com/rabbitmq/amqp091-go"
"github.com/rs/zerolog/log"
)
var (
rabbitConn *amqp091.Connection
rabbitChannel *amqp091.Channel
rabbitEnabled bool
rabbitOnce sync.Once
rabbitQueue string
)
// Call this in main() or initialization
func InitRabbitMQ() {
rabbitURL := os.Getenv("RABBITMQ_URL")
rabbitQueue = os.Getenv("RABBITMQ_QUEUE")
if rabbitQueue == "" {
rabbitQueue = "whatsapp_events" // default queue
}
if rabbitURL == "" {
rabbitEnabled = false
log.Info().Msg("RABBITMQ_URL is not set. RabbitMQ publishing disabled.")
return
}
var err error
rabbitConn, err = amqp091.Dial(rabbitURL)
if err != nil {
rabbitEnabled = false
log.Error().Err(err).Msg("Could not connect to RabbitMQ")
return
}
rabbitChannel, err = rabbitConn.Channel()
if err != nil {
rabbitEnabled = false
log.Error().Err(err).Msg("Could not open RabbitMQ channel")
return
}
rabbitEnabled = true
log.Info().
Str("queue", rabbitQueue).
Msg("RabbitMQ connection established.")
}
// Optionally, allow overriding the queue per message
func PublishToRabbit(data []byte, queueOverride ...string) error {
if !rabbitEnabled {
return nil
}
queueName := rabbitQueue
if len(queueOverride) > 0 && queueOverride[0] != "" {
queueName = queueOverride[0]
}
// Declare queue (idempotent)
_, err := rabbitChannel.QueueDeclare(
queueName,
true, // durable
false, // auto-delete
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Error().Err(err).Str("queue", queueName).Msg("Could not declare RabbitMQ queue")
return err
}
err = rabbitChannel.Publish(
"", // exchange (default)
queueName, // routing key = queue
false, // mandatory
false, // immediate
amqp091.Publishing{
ContentType: "application/json",
Body: data,
},
)
if err != nil {
log.Error().Err(err).Str("queue", queueName).Msg("Could not publish to RabbitMQ")
} else {
log.Debug().Str("queue", queueName).Msg("Published message to RabbitMQ")
}
return err
}
// Usage - like sendToGlobalWebhook
func sendToGlobalRabbit(jsonData []byte, queueName ...string) {
if !rabbitEnabled {
log.Debug().Msg("RabbitMQ publishing is disabled, not sending message")
return
}
err := PublishToRabbit(jsonData, queueName...)
if err != nil {
log.Error().Err(err).Msg("Failed to publish to RabbitMQ")
}
}