/
publisher.go
90 lines (75 loc) · 1.83 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
package pamqp
import (
"context"
"github.com/streadway/amqp"
"google.golang.org/protobuf/proto"
)
// Publisher represents a message publisher
type Publisher struct {
channel Channel
exchangeNameFn func(proto.Message) (string, error)
routingKeyFn func(proto.Message) (string, error)
middlewareFn MiddlewareFunc
}
// NewPublisher returns a new publisher
func NewPublisher(c *amqp.Connection, optFns ...func(*Options)) (*Publisher, error) {
o := defaultOptions
for _, fn := range optFns {
fn(&o)
}
ch, err := o.ChannelFn(c)
if err != nil {
return nil, err
}
return &Publisher{
channel: ch,
exchangeNameFn: o.ExchangeNameFn,
routingKeyFn: o.RoutingKeyFn,
middlewareFn: o.MiddlewareFn,
}, nil
}
// Publish publishes the specified message
func (p *Publisher) Publish(ctx context.Context, m proto.Message, mdFns ...func(*Metadata)) error {
md := Metadata{
ID: NewID(),
Type: MessageName(m),
ContentType: "application/protobuf",
Timestamp: UTCNow(),
Headers: map[string]interface{}{},
}
for _, fn := range mdFns {
fn(&md)
}
hfn := p.handlePublish
if p.middlewareFn != nil {
hfn = p.middlewareFn(hfn)
}
return hfn(ctx, m, md)
}
// Close closes the underlying channel
func (p *Publisher) Close() error {
return p.channel.Close()
}
func (p *Publisher) handlePublish(ctx context.Context, m proto.Message, md Metadata) error {
e, err := p.exchangeNameFn(m)
if err != nil {
return err
}
k, err := p.routingKeyFn(m)
if err != nil {
return err
}
b, err := proto.Marshal(m)
if err != nil {
return err
}
return p.channel.Publish(e, k, false, false, amqp.Publishing{
Headers: md.Headers,
Body: b,
ContentType: md.ContentType,
MessageId: md.ID,
CorrelationId: md.CorrelationID,
Type: md.Type,
Timestamp: md.Timestamp,
})
}