/
publisher.go
59 lines (56 loc) · 1.68 KB
/
publisher.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
package rabbitmq
import (
"fmt"
"github.com/pkg/errors"
"github.com/streadway/amqp"
"go.mongodb.org/mongo-driver/bson"
"time"
)
//Publish publishes a request to the amqp queue
func (c *Connection) Publish(exchange, routingKey string, body interface{}, publishOptions PublishingOptions) error {
if !checkElementInSlice(c.exchanges, exchange) {
return EXHCNAGE_NOT_FOUND_ERROR
}
// serialized event to bson
b, err := bson.Marshal(body)
if err != nil {
return err
}
// try to publish event
if err := publish(c, exchange, routingKey, b, publishOptions); err != nil {
if errors.Is(err, CONNECTION_CLOSED_ERROR) {
for {
if c.isConnected {
break
}
time.Sleep(1 * time.Second)
}
}
return err
}
return nil
}
func publish(conn *Connection, exchange, routingKey string, body []byte, publishingOptions PublishingOptions) error {
if !conn.isConnected {
return CONNECTION_CLOSED_ERROR
}
p := amqp.Publishing{
Headers: amqp.Table(publishingOptions.Headers),
ContentType: publishingOptions.ContentType,
ContentEncoding: publishingOptions.ContentEncoding,
DeliveryMode: publishingOptions.DeliveryMode,
Priority: publishingOptions.Priority,
CorrelationId: publishingOptions.CorrelationId,
ReplyTo: publishingOptions.ReplyTo,
Expiration: publishingOptions.Expiration,
MessageId: publishingOptions.MessageId,
Timestamp: publishingOptions.Timestamp,
UserId: publishingOptions.UserId,
AppId: publishingOptions.AppId,
Body: body,
}
if err := conn.channel.Publish(exchange, routingKey, false, false, p); err != nil {
return fmt.Errorf("error in Publishing: %s", err)
}
return nil
}