package main
import (
"flag"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"os/signal"
"syscall"
"fmt"
"os"
)
func main() {
profile := flag.String("p", "", "AWSの認証に使うProfile。未指定ならdefault")
queue := flag.String("q", "", "The name of the queue")
flag.Parse()
if *queue == "" {
fmt.Println("You must supply the name of a queue (-q QUEUE)")
return
}
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file. (~/.aws/credentials).
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
Profile: *profile,
}))
svc := sqs.New(sess)
urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
QueueName: queue,
})
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
go func() {
queueURL := urlResult.QueueUrl
timeout := int64(20)
for {
msgResult, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
AttributeNames: []*string{
aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
aws.String(sqs.MessageSystemAttributeNameSenderId),
},
MessageAttributeNames: []*string{
aws.String(sqs.QueueAttributeNameAll),
},
QueueUrl: queueURL,
MaxNumberOfMessages: aws.Int64(1),
VisibilityTimeout: &timeout,
WaitTimeSeconds: &timeout, // ロングポーリング
})
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
for _, message := range msgResult.Messages {
fmt.Println(message)
// 一度受け取ったメッセージはキューから削除。そうしないと何回も受信してしまう
_, _ = svc.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: queueURL,
ReceiptHandle: message.ReceiptHandle,
})
}
}
}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
s := <-sig
fmt.Printf("Signal received: %s \n", s.String())
}