forked from Romaixn/gosumer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amqp_transport.go
96 lines (76 loc) · 1.42 KB
/
amqp_transport.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
package gosumer
import (
"fmt"
"log"
amqp "github.com/rabbitmq/amqp091-go"
)
type RabbitMQ struct {
Host string
Port *uint8
User string
Password string
Queue string
}
var connection *amqp.Connection
var channel *amqp.Channel
func (rabbitmq RabbitMQ) connect() error {
var err error
if rabbitmq.Port != nil {
connection, err = amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%d/%s", rabbitmq.User, rabbitmq.Password, rabbitmq.Host, rabbitmq.Port, "%2f"))
} else {
connection, err = amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s/%s", rabbitmq.User, rabbitmq.Password, rabbitmq.Host, "%2f"))
}
if err != nil {
return err
}
channel, err = connection.Channel()
if err != nil {
return err
}
return nil
}
func (rabbitmq RabbitMQ) listen(fn process, message any) error {
err := rabbitmq.connect()
if err != nil {
return err
}
defer connection.Close()
defer channel.Close()
q, err := channel.QueueDeclare(
rabbitmq.Queue,
true,
false,
false,
false,
nil,
)
if err != nil {
return err
}
msgs, err := channel.Consume(
q.Name,
"",
true,
false,
false,
false,
nil,
)
if err != nil {
return err
}
log.Printf("Successfully connected to the queue!")
var forever chan struct{}
go func() {
for d := range msgs {
msg, err := formatMessage(string(d.Body), message)
if err != nil {
log.Fatal(err)
}
var e chan error
go fn(msg, e)
}
}()
<-forever
return nil
}