AWS SQS: Amazon Simple Queue Service (SQS) is a fully managed message queuing service that enables you to decouple and scale microservices, distributed systems, and serverless applications.
Some time we may need to send messages to AWS SQS along with message meta data. I use a simple program written in golang to post a message.
As we do with all AWS programmatic access, we need to create session
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Then we need to get the SQS queue url from the queue name
func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) {
// Create an SQS service client
svc := sqs.New(sess)
result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
QueueName: queue,
})
if err != nil {
return nil, err
}
return result, nil
}
You can attach metadata to the message while posting it to the SQS queue
func SendMsg(sess *session.Session, data string, id string, msgType string, queueURL *string) error {
// Create an SQS service client
svc := sqs.New(sess)
var err error
_, err = svc.SendMessage(&sqs.SendMessageInput{
MessageAttributes: map[string]*sqs.MessageAttributeValue{
"msgType": {
DataType: aws.String("String"),
StringValue: aws.String(msgType),
},
"id": {
DataType: aws.String("String"),
StringValue: aws.String(id),
},
},
MessageBody: aws.String(data),
QueueUrl: queueURL,
})
if err != nil {
return err
}
return nil
}
The whole code can be found at github repo https://github.com/arunx2/golang-samples/blob/main/publish-to-sqs/main.go
Top comments (0)