-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsender.go
127 lines (102 loc) · 2.52 KB
/
sender.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package messenger_amqp
import (
"context"
"errors"
"strconv"
"time"
"github.com/riid/messenger"
"github.com/riid/messenger/envelope"
"github.com/streadway/amqp"
)
type PublishArgs struct {
Exchange string
Mandatory bool
Immediate bool
}
func Sender(channel Channel, publishArgs PublishArgs) *sender {
return &sender{
channel: channel,
publishArgs: publishArgs,
}
}
type sender struct {
channel Channel
publishArgs PublishArgs
}
func (s *sender) Send(_ context.Context, e messenger.Envelope) error {
routingKey := RoutingKey(e)
e = WithoutRoutingKey(e)
msg, err := createAMQPMessageFromEnvelope(e)
if err != nil {
return err
}
err = s.channel.Publish(
s.publishArgs.Exchange,
routingKey,
s.publishArgs.Mandatory,
s.publishArgs.Immediate,
msg,
)
if err != nil {
return err
}
return nil
}
func createAMQPMessageFromEnvelope(e messenger.Envelope) (amqp.Publishing, error) {
body, ok := e.Message().([]byte)
if !ok {
return amqp.Publishing{}, errors.New("message must be []byte")
}
contentType := envelope.ContentType(e)
e = envelope.WithoutContentType(e)
correlationID := envelope.CorrelationID(e)
e = envelope.WithoutCorrelationID(e)
replyTo := envelope.ReplyTo(e)
e = envelope.WithoutReplyTo(e)
expiration, err := envelope.Expiration(e)
expirationStr := ""
if err == nil {
expirationStr = strconv.FormatInt(expiration.Milliseconds(), 10)
}
e = envelope.WithoutExpiration(e)
id := envelope.ID(e)
e = envelope.WithoutID(e)
timestamp, err := envelope.Timestamp(e)
if err == envelope.ErrNoTimestamp {
timestamp = time.Time{}
} else if err != nil {
return amqp.Publishing{}, err
}
e = envelope.WithoutTimestamp(e)
userID := envelope.UserID(e)
e = envelope.WithoutUserID(e)
appID := envelope.AppID(e)
e = envelope.WithoutAppID(e)
messageType := envelope.MessageType(e)
e = envelope.WithoutMessageType(e)
priority := uint8(envelope.Priority(e))
e = envelope.WithoutPriority(e)
envelopeHeaders := e.Headers()
headers := make(amqp.Table, len(envelopeHeaders))
for name, hh := range envelopeHeaders {
ii := make([]interface{}, len(hh))
for i := 0; i < len(ii); i++ {
ii[i] = hh[i]
}
headers[name] = ii
}
return amqp.Publishing{
Headers: headers,
ContentType: contentType,
Priority: priority,
CorrelationId: correlationID,
ReplyTo: replyTo,
Expiration: expirationStr,
MessageId: id,
Timestamp: timestamp,
Type: messageType,
UserId: userID,
AppId: appID,
Body: body,
}, nil
}