-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe.go
80 lines (73 loc) · 1.47 KB
/
subscribe.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
package broker
import (
"bytes"
"errors"
"time"
"github.com/sirupsen/logrus"
)
func (eq *eventQueue) subscribe(event string, handle *handler, done chan<- doneErrCh) {
// Open new channel
ch, err := eq.conn.Channel()
if err != nil {
done <- doneErrCh{event, err}
return
}
defer ch.Close()
// Exchange Declaration
if err := ch.ExchangeDeclare(
event,
"topic",
true,
false,
false,
false,
nil,
); err != nil {
done <- doneErrCh{event, err}
return
}
// Queue Dleclaration
_, err = ch.QueueDeclare(
handle.Options.QueueName,
true,
false,
false,
false,
nil,
)
if err != nil {
done <- doneErrCh{event, err}
return
}
// Binding Declaration
if err := ch.QueueBind(handle.Options.QueueName, handle.Options.RouteKey, event, false, nil); err != nil {
done <- doneErrCh{event, err}
return
}
msgs, err := ch.Consume(
handle.Options.QueueName,
"",
false,
false,
false,
false,
nil,
)
if err != nil {
done <- doneErrCh{event, err}
return
}
logrus.Infof("waiting to receive messages from %v event", event)
for d := range msgs {
_, err := handle.HandleFn(&Request{Body: bytes.NewBuffer(d.Body)})
if err != nil {
logrus.WithField("event", event).Errorf("failed to perform message: %v; waiting 5 seconds to try again...", err)
time.Sleep(10 * time.Second)
d.Nack(false, true)
continue
}
// TODO: validate response to publish another event
d.Ack(false)
}
done <- doneErrCh{event, errors.New("channel is closed")}
}