push payload to sqs topic in go

To push a payload to an SQS topic in Go, you can use the AWS SDK for Go. Here's an example code snippet that demonstrates how to send a message to an SQS topic:

main.go
package main

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sqs"
	"log"
)

func main() {
	// Set up a session
	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))
	// Create an SQS service client
	svc := sqs.New(sess)

	// Define the message to send
	message := "Hello, world!"

	// Set up the input for the SendMessage function
	input := &sqs.SendMessageInput{
		MessageBody:            aws.String(message),
		MessageGroupId:         aws.String("my-group"),
		MessageDeduplicationId: aws.String("my-dedup"),
		TopicArn:               aws.String("arn:aws:sns:us-east-1:123456789012:my-topic"),
	}

	// Send the message to the SQS topic
	result, err := svc.SendMessage(input)
	if err != nil {
		log.Println("Error sending message to SQS topic:", err)
		return
	}

	// Print out the message ID
	fmt.Println("Message ID:", *result.MessageId)
}
991 chars
40 lines

In this code snippet, we first set up an AWS session using shared configuration. Then, we create a new sqs.SQS client using that session.

Next, we define the message that we want to send in the message variable.

We set up the input for the SendMessage function by creating a new sqs.SendMessageInput object and populating its fields. We specify the message body, a message group ID, a message deduplication ID, and the ARN of the SQS topic.

Finally, we call the SendMessage function on our SQS client, passing in the input object. The function returns a SendMessageOutput object, from which we can extract the ID of the sent message. We print out this ID for verification.

Note that this code assumes that you have already set up your AWS credentials and region using environment variables or other means.

gistlibby LogSnag