Skip to content

Instantly share code, notes, and snippets.

@RafPe
Created August 29, 2019 09:17
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save RafPe/4e6849cd9a54bc0ce3a9cc0d8c2c7d41 to your computer and use it in GitHub Desktop.
Save RafPe/4e6849cd9a54bc0ce3a9cc0d8c2c7d41 to your computer and use it in GitHub Desktop.
SQS Polling with golang channels
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"fmt"
)
var (
sqsSvc *sqs.SQS
)
func pollMessages(chn chan<- *sqs.Message) {
for {
output, err := sqsSvc.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: aws.String("https://sqs.eu-central-1.amazonaws.com/123456/rafpe"),
MaxNumberOfMessages: aws.Int64(2),
WaitTimeSeconds: aws.Int64(15),
})
if err != nil {
fmt.Println("failed to fetch sqs message %v", err)
}
for _, message := range output.Messages {
chn <- message
}
}
}
func handleMessage(msg *sqs.Message) {
fmt.Println("RECEIVING MESSAGE >>> ")
fmt.Println(*msg.Body)
}
func deleteMessage(msg *sqs.Message) {
sqsSvc.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: aws.String("https://sqs.eu-central-1.amazonaws.com/123456/rafpe"),
ReceiptHandle: msg.ReceiptHandle,
})
}
func main() {
// 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{Config: aws.Config{Region: aws.String("eu-central-1")}, Profile: "xyz"}))
sqsSvc = sqs.New(sess)
chnMessages := make(chan *sqs.Message, 2)
go pollMessages(chnMessages)
for message := range chnMessages {
handleMessage(message)
deleteMessage(message)
}
}
@VishwasShashidhar
Copy link

This was super useful! Thank you @RafPe 👍

@okaforcj
Copy link

okaforcj commented Mar 8, 2022

thanks for this! you're an angel

@vranystepan
Copy link

The best example. Much better than the official Amazon examples. Thank you very much!

@RafPe
Copy link
Author

RafPe commented Oct 31, 2023

Happy could help 😊 sharing is caring

@silasstoffel
Copy link

Very good, thanks for sharing with us!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment