This repository has been archived by the owner on Feb 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathrabbit.go
87 lines (75 loc) · 1.73 KB
/
rabbit.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
package main
import (
"encoding/json"
"errors"
"log"
"os"
"time"
"github.com/streadway/amqp"
"github.com/thethingsnetwork/server-shared"
)
const (
RABBIT_ATTEMPTS = 20
RABBIT_EXCHANGE = "messages"
)
type RabbitPublisher struct {
conn *amqp.Connection
channel *amqp.Channel
}
func ConnectRabbitPublisher() (Publisher, error) {
var err error
for i := 0; i < RABBIT_ATTEMPTS; i++ {
uri := os.Getenv("AMQP_URI")
conn, err := amqp.Dial(uri)
if err != nil {
log.Printf("Failed to connect: %s", err.Error())
time.Sleep(time.Duration(2) * time.Second)
} else {
publisher := &RabbitPublisher{conn, nil}
log.Printf("Connected to %s", uri)
return publisher, nil
}
}
return nil, err
}
func (p *RabbitPublisher) Configure() error {
c, err := p.conn.Channel()
if err != nil {
log.Printf("Failed to open channel: %v", err)
return err
}
err = c.ExchangeDeclare(RABBIT_EXCHANGE, "topic", true, false, false, false, nil)
if err != nil {
log.Printf("Failed to declare exchange: %v", err)
return err
}
p.channel = c
return nil
}
func (p *RabbitPublisher) Publish(data interface{}) error {
body, err := json.Marshal(data)
if err != nil {
log.Printf("Failed to marshal data: %s", err.Error())
return err
}
msg := amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "application/json",
Body: body,
}
var routingKey string
switch data.(type) {
case *shared.GatewayStatus:
routingKey = "gateway.status"
case *shared.RxPacket:
routingKey = "gateway.rx"
default:
return errors.New("Invalid type to publish")
}
err = p.channel.Publish(RABBIT_EXCHANGE, routingKey, false, false, msg)
if err != nil {
log.Printf("Failed to publish: %s", err.Error())
return err
}
return nil
}