Menu
AWS SDK for Go
Developer Guide

Sending and Receiving Messages in Amazon SQS

These AWS SDK for Go examples show you how to:

  • Send a message to an Amazon SQS queue

  • Receive and delete a message from an Amazon SQS queue

  • Send and receive messages from an Amazon SQS queue

You can download complete versions of these example files from the aws-doc-sdk-examples repository on GitHub.

The Scenario

These examples demonstrate sending, receiving, and deleting messages from an Amazon SQS queue.

The code uses these methods of the Amazon SQS client class:

Prerequisites

Send a Message to a Queue

Create a new Go file named sqs_sendmessage.go.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

Copy
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" )

Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/credentials.

Copy
func main() { sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) svc := sqs.New(sess) // URL to our queue qURL := "QueueURL"

Now you're ready to send your message. In the example, the message input passed to SendMessage represents information about a fiction best seller for a particular week and defines title, author, and weeks on the list values.

Copy
result, err := svc.SendMessage(&sqs.SendMessageInput{ DelaySeconds: aws.Int64(10), MessageAttributes: map[string]*sqs.MessageAttributeValue{ "Title": &sqs.MessageAttributeValue{ DataType: aws.String("String"), StringValue: aws.String("The Whistler"), }, "Author": &sqs.MessageAttributeValue{ DataType: aws.String("String"), StringValue: aws.String("John Grisham"), }, "WeeksOn": &sqs.MessageAttributeValue{ DataType: aws.String("Number"), StringValue: aws.String("6"), }, }, MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), QueueUrl: &qURL, }) if err != nil { fmt.Println("Error", err) return } fmt.Println("Success", *result.MessageId) }

Receive and Delete a Message from a Queue

Create a new Go file named sqs_deletemessage.go.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

Copy
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" )

Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/credentials.

Copy
func main() { sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) svc := sqs.New(sess)

Now you're ready to receive a message from a queue specified by a queue URL. In the example, the qURL variable would hold the URL for the queue containing the message.

Copy
qURL := "QueueURL" result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ AttributeNames: []*string{ aws.String(sqs.MessageSystemAttributeNameSentTimestamp), }, MessageAttributeNames: []*string{ aws.String(sqs.QueueAttributeNameAll), }, QueueUrl: &qURL, MaxNumberOfMessages: aws.Int64(1), VisibilityTimeout: aws.Int64(36000), // 10 hours WaitTimeSeconds: aws.Int64(0), }) if err != nil { fmt.Println("Error", err) return } if len(result.Messages) == 0 { fmt.Println("Received no messages") return }

After retrieving the message, delete it from the queue with DeleteMessage, passing the ReceiptHandle returned from the previous call.

Copy
resultDelete, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ QueueUrl: &qURL, ReceiptHandle: result.Messages[0].ReceiptHandle, }) if err != nil { fmt.Println("Delete Error", err) return } fmt.Println("Message Deleted", resultDelete) }

Send and Receive Messages

Create a new Go file named sqs_longpolling_receive_message.go.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

Copy
package main import ( "flag" "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" )

Get the queue name and timeout passed from the command.

Copy
func main() { var name string var timeout int64 flag.StringVar(&name, "n", "", "Queue name") flag.Int64Var(&timeout, "t", 20, "(Optional) Timeout in seconds for long polling") flag.Parse() if len(name) == 0 { flag.PrintDefaults() exitErrorf("Queue name required") }

Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/credentials.

Copy
sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) // Create a SQS service client. svc := sqs.New(sess)

Get the Queue. You need to convert the queue name into a URL. You can use the GetQueueUrl API call to retrieve the URL. This is needed for receiving messages from the queue. Print any errors.

Copy
resultURL, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ QueueName: aws.String(name), }) if err != nil { if aerr, ok := err.(awserr.Error); ok && aerr.Code() == sqs.ErrCodeQueueDoesNotExist { exitErrorf("Unable to find queue %q.", name) } exitErrorf("Unable to queue %q, %v.", name, err) }

Call ReceiveMessage to get the latest message from the queue.

Copy
result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ QueueUrl: resultURL.QueueUrl, AttributeNames: aws.StringSlice([]string{ "SentTimestamp", }), MaxNumberOfMessages: aws.Int64(1), MessageAttributeNames: aws.StringSlice([]string{ "All", }), WaitTimeSeconds: aws.Int64(timeout), }) if err != nil { exitErrorf("Unable to receive message from queue %q, %v.", name, err) } fmt.Printf("Received %d messages.\n", len(result.Messages)) if len(result.Messages) > 0 { fmt.Println(result.Messages) } }

The example uses this utility function.

Copy
func exitErrorf(msg string, args ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", args...) os.Exit(1) }