-
Notifications
You must be signed in to change notification settings - Fork 1
/
producer.go
75 lines (63 loc) · 1.79 KB
/
producer.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
package gosqs
import (
"context"
"encoding/json"
"time"
"github.com/engelmi/go-sqs/internal"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/pkg/errors"
)
type Producer interface {
Send(ctx context.Context, msg OutgoingMessage) (*string, error)
}
type producer struct {
*internal.Client
timeout time.Duration
}
func NewProducer(config ProducerConfig) (Producer, error) {
c, err := internal.NewClient(config.Region, config.Endpoint, config.Queue)
if err != nil {
return nil, err
}
return &producer{
Client: c,
timeout: config.Timeout,
}, nil
}
func (p *producer) Send(ctx context.Context, msg OutgoingMessage) (*string, error) {
timeoutCtx, cancel := context.WithTimeout(context.Background(), p.timeout)
defer cancel()
output, err := p.Sqs.SendMessageWithContext(timeoutCtx, p.mapToAwsMessage(msg))
if err != nil {
return nil, errors.Wrap(err, "Failed to send message")
}
return output.MessageId, nil
}
func (p *producer) mapToAwsMessage(msg OutgoingMessage) *sqs.SendMessageInput {
payload := string(msg.Payload)
input := &sqs.SendMessageInput{
QueueUrl: aws.String(p.QueueUrl),
MessageBody: aws.String(payload),
MessageGroupId: msg.GroupId,
MessageDeduplicationId: msg.DeduplicationId,
}
if msg.Attributes != nil {
attributes := make(map[string]*sqs.MessageAttributeValue)
for key, value := range msg.Attributes {
attributes[key] = &sqs.MessageAttributeValue{
DataType: aws.String("String"),
StringValue: aws.String(value),
}
}
input.MessageAttributes = attributes
}
return input
}
func MarshalToJson(payload interface{}) ([]byte, error) {
bytes, err := json.Marshal(payload)
if err != nil {
return nil, errors.Wrap(err, "Failed to marshal payload")
}
return bytes, nil
}