This repository has been archived by the owner on May 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpublisher.go
92 lines (63 loc) · 1.48 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
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
package dispatcher
import (
"encoding/json"
"errors"
"github.com/satori/go.uuid"
"github.com/streadway/amqp"
)
type publisher struct {
log Log
ch *amqp.Channel
confirmationChan chan amqp.Confirmation
active bool
defaultExchange string
defaultRoutingKey string
}
func (s *publisher) init(con *amqp.Connection) error {
s.log.Debug("Publisher initialization")
ch, err := con.Channel()
if err != nil {
return err
}
s.ch = ch
if err = s.ch.Confirm(false); err != nil {
return err
}
s.confirmationChan = s.ch.NotifyPublish(make(chan amqp.Confirmation, 1))
s.active = true
s.log.Debug("Publisher is ready")
return nil
}
func (s *publisher) deactivate() {
s.log.Debug("Deactivating publisher")
s.active = false
s.ch.Close()
s.log.Debug("Publisher is deactivated")
}
// Publish method is used for publishing tasks.
func (s *publisher) Publish(task *Task) error {
if task.RoutingKey == "" {
task.RoutingKey = s.defaultRoutingKey
}
if task.UUID == "" {
task.UUID = uuid.NewV4().String()
}
if task.Name == "" {
return errors.New("Task name was not passed")
}
msg, err := json.Marshal(task)
if err != nil {
return err
}
if !s.active {
return errors.New("Service is disconnected")
}
if err := publishMessage(s.ch, s.defaultExchange, task.RoutingKey, task.Headers, msg); err != nil {
return err
}
confirmed := <-s.confirmationChan
if confirmed.Ack {
return nil
}
return errors.New("Failed to deliver message")
}