-
Notifications
You must be signed in to change notification settings - Fork 9
/
sqs_client.go
95 lines (77 loc) · 2.12 KB
/
sqs_client.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
package main
import (
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
// SQSClient is an interface for SQS
type SQSClient interface {
// Fetch returns the next batch of SQS messages
Fetch() ([]Message, error)
// Delete deletes a single message from SQS
Delete(Message) error
}
// Message is the internal representation of an SQS message
type Message struct {
MessageID string
Body string
ReceiptHandle string
}
type sdkClient struct {
service *sqs.SQS
url string
SQSConfig
}
// NewAWSSQSClient creates an SQS client that talks to AWS on the given queue
func NewAWSSQSClient(conf AWSConfig, queueName string, sqsConf SQSConfig) (SQSClient, error) {
creds := credentials.NewStaticCredentials(conf.AccessKey, conf.SecretKey, "")
sess, err := session.NewSession(&aws.Config{Region: formatRegion(conf.Region), Credentials: creds})
if err != nil {
return nil, err
}
client := &sdkClient{
service: sqs.New(sess),
SQSConfig: sqsConf,
}
resp, err := client.service.GetQueueUrl(&sqs.GetQueueUrlInput{
QueueName: &queueName,
})
if err != nil {
return nil, err
}
client.url = *resp.QueueUrl
return client, nil
}
func (s *sdkClient) Fetch() ([]Message, error) {
res, err := s.service.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: &s.url,
MaxNumberOfMessages: &s.maxNumberOfMessages,
WaitTimeSeconds: &s.waitTimeSeconds,
VisibilityTimeout: &s.visibilityTimeout,
})
if err != nil {
return nil, err
}
msgs := make([]Message, len(res.Messages))
for i, m := range res.Messages {
msgs[i] = Message{
MessageID: *m.MessageId,
Body: *m.Body,
ReceiptHandle: *m.ReceiptHandle,
}
}
return msgs, nil
}
func (s *sdkClient) Delete(message Message) error {
_, err := s.service.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: &s.url,
ReceiptHandle: &message.ReceiptHandle,
})
return err
}
func formatRegion(region string) *string {
newRegion := strings.NewReplacer(".", "-", "_", "-").Replace(region)
return &newRegion
}