Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
var (
queue_url = "YOUR_QUEUE_URL"
)
func main() {
// Initalize a sqs handler
sess, err := session.NewSession(&aws.Config{Region: aws.String("YOUR_REGION")})
if err != nil {
log.Fatal(err)
}
svc := sqs.New(sess)
messages := []string{
"I dont know what happen",
"What do I need to learn today",
"This is so delicious",
"You look so cute",
}
for _, v := range messages {
sendMessage(svc, v)
}
time.Sleep(10 * time.Second)
readMessage(svc)
}
func sendMessage(svc *sqs.SQS, content string) {
result, err := svc.SendMessage(&sqs.SendMessageInput{
DelaySeconds: aws.Int64(10),
MessageBody: aws.String(content),
QueueUrl: &queue_url,
})
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", *result.MessageId)
}
func readMessage(svc *sqs.SQS) {
ticker := time.NewTicker(time.Second)
for range ticker.C {
result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: &queue_url,
MaxNumberOfMessages: aws.Int64(1),
VisibilityTimeout: aws.Int64(20), // 20 seconds
WaitTimeSeconds: aws.Int64(0),
})
if err != nil {
fmt.Println("Error", err)
return
}
if len(result.Messages) == 0 {
fmt.Println("Received no messages")
return
}
fmt.Println("output:")
for _, v := range result.Messages {
fmt.Println(*v.Body)
}
// delete
resultDelete, err := svc.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: &queue_url,
ReceiptHandle: result.Messages[0].ReceiptHandle,
})
if err != nil {
fmt.Println("Delete Error", err)
return
}
fmt.Println("Message Deleted", resultDelete)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment