-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqsbuddy.go
More file actions
86 lines (75 loc) · 1.55 KB
/
sqsbuddy.go
File metadata and controls
86 lines (75 loc) · 1.55 KB
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
package iotdaemon
import (
"context"
"log"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sqs"
)
const (
maxMessages = 1
longPoll = 20
)
type SQSBuddy struct {
Config aws.Config
Context context.Context
Url string
Logger *log.Logger
_queue chan *string
_init sync.Once
}
// Poll runs a background thread and continuously grabs strings from SQS.
func (s *SQSBuddy) Poll() <-chan *string {
s.doInit()
return s._queue
}
func (s *SQSBuddy) doPoll() {
client := sqs.NewFromConfig(s.Config)
req := &sqs.ReceiveMessageInput{
QueueUrl: &s.Url,
MaxNumberOfMessages: maxMessages,
WaitTimeSeconds: longPoll,
}
for {
select {
case <-s.Context.Done():
close(s._queue)
return
default:
res, err := client.ReceiveMessage(s.Context, req)
if err != nil {
s.Logger.Println("error polling: ", err.Error())
time.Sleep(30 * time.Second)
continue
}
for _, message := range res.Messages {
s._queue <- message.Body
_, err = client.DeleteMessage(context.Background(), &sqs.DeleteMessageInput{
QueueUrl: &s.Url,
ReceiptHandle: message.ReceiptHandle,
})
if err != nil {
s.Logger.Println("error deleting: ", err.Error())
}
}
// empty, retry
}
}
}
func (s *SQSBuddy) doInit() {
s._init.Do(func() {
if s.Context == nil {
s.Context = context.Background()
}
if s.Logger == nil {
s.Logger = log.Default()
}
s._queue = make(chan *string, 1)
if s.Url == "" {
close(s._queue)
return
}
go s.doPoll()
})
}