

AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/).

# Amazon SQS Examples Using the AWS SDK for Go
<a name="using-sqs-with-go-sdk"></a>

Amazon Simple Queue Service (Amazon SQS) is a fully managed message queuing service that makes it easy to decouple and scale microservices, distributed systems, and serverless applications. The AWS SDK for Go examples can integrate Amazon SQS into your applications. The examples assume you have already set up and configured the SDK (that is, you’ve imported all required packages and set your credentials and region). For more information, see [Getting Started with the AWS SDK for Go](setting-up.md) and [Configuring the AWS SDK for Go](configuring-sdk.md).

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/sqs) repository on GitHub.

**Topics**
+ [Using Amazon SQS Queues](sqs-example-create-queue.md)
+ [Sending and Receiving Messages in Amazon SQS](sqs-example-receive-message.md)
+ [Managing Visibility Timeout in Amazon SQS Queues](sqs-example-managing-visibility-timeout.md)
+ [Enabling Long Polling in Amazon SQS Queues](sqs-example-enable-long-polling.md)
+ [Using Dead Letter Queues in Amazon SQS](sqs-example-dead-letter-queues.md)

# Using Amazon SQS Queues
<a name="sqs-example-create-queue"></a>

These AWS SDK for Go examples show you how to:
+ List Amazon SQS queues
+ Create Amazon SQS queues
+ Get Amazon SQS queue URLs
+ Delete Amazon SQS queues

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/sqs) repository on GitHub.

## Scenario
<a name="sqs-create-scenario"></a>

These examples demonstrate how to work with Amazon SQS queues.

The code uses these methods of the Amazon SQS client class:
+  [CreateQueue](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.CreateQueue) 
+  [ListQueues](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.ListQueues) 
+  [GetQueueUrl](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.GetQueueUrl) 
+  [DeleteQueue](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.DeleteQueue) 

## Prerequisites
<a name="sqs-create-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with using Amazon SQS. To learn more, see [How Queues Work](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-how-it-works.html) in the Amazon SQS Developer Guide.

## List Queues
<a name="sqs-example-list-queues"></a>

Create a new Go file named `ListQueues.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `ListQueues`, passing in `nil` to return all queues.

```
svc := sqs.New(sess)

result, err := svc.ListQueues(nil)
```

Loop through the queue URLs to print them.

```
for i, url := range result.QueueUrls {
    fmt.Printf("%d: %s\n", i, *url)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/ListQueues/ListQueues.go) on GitHub.

## Create a Queue
<a name="create-a-queue"></a>

Create a new Go file named `CreateQueue.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the queue name from the command line.

```
queue := flag.String("q", "", "The name of the queue")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply a queue name (-q QUEUE")
    return
}
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `CreateQueue`, passing in the queue name and queue attributes.

```
svc := sqs.New(sess)

result, err := svc.CreateQueue(&sqs.CreateQueueInput{
    QueueName: queue,
    Attributes: map[string]*string{
        "DelaySeconds":           aws.String("60"),
        "MessageRetentionPeriod": aws.String("86400"),
    },
})
```

Display the queue URL.

```
fmt.Println("URL: " + *result.QueueUrl)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/CreateQueue/CreateQueue.go) on GitHub.

## Get the URL of a Queue
<a name="get-the-url-of-a-queue"></a>

Create a new Go file named `GetQueueUrl.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the name of the queue from the command line.

```
queue := flag.String("q", "", "The name of the queue")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply a queue name (-q QUEUE")
    return
}
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `GetQueueUrl`, passing in the queue name.

```
svc := sqs.New(sess)

result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queue,
})
```

Display the URL of the queue.

```
fmt.Println("URL: " + *result.QueueUrl)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/GetQueueURL/GetQueueURL.go) on GitHub.

## Delete a Queue
<a name="delete-a-queue"></a>

Create a new Go file named `DeleteQueue.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the name of the queue from the command line.

```
queue := flag.String("q", "", "The name of the queue")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply a queue name (-q QUEUE")
    return
}
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and all `DeleteQueue` passing in the queue name.

```
svc := sqs.New(sess)

result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queueName,
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/DeleteQueue/DeleteQueue.go) on GitHub.

# Sending and Receiving Messages in Amazon SQS
<a name="sqs-example-receive-message"></a>

These AWS SDK for Go examples show you how to:
+ Send a message to an Amazon SQS queue
+ Receive a message from an Amazon SQS queue
+ Delete a message from an Amazon SQS queue

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/sqs) repository on GitHub.

## The Scenario
<a name="sqs-receive-message-scenario"></a>

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

The code uses these methods of the Amazon SQS client class:
+  [SendMessage](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.SendMessage) 
+  [ReceiveMessage](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.ReceiveMessage) 
+  [DeleteMessage](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.DeleteMessage) 
+  [GetQueueUrl](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.GetQueueUrl) 

## Prerequisites
<a name="sqs-receive-message-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with the details of Amazon SQS messages. To learn more, see [Sending a Message to an Amazon SQS Queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-send-message.html) and [Receiving and Deleting a Message from an Amazon SQS Queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-receive-delete-message.html) in the Amazon SQS Developer Guide.

## Send a Message to a Queue
<a name="sqs-example-send-message"></a>

Create a new Go file named `SendMessage.go`.

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

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the name of the queue from the command line.

```
queue := flag.String("q", "", "The name of the queue")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply the name of a queue (-q QUEUE)")
    return
}
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call *SendMessage*. The input represents information about a fiction best seller for a particular week and defines title, author, and weeks on the list values.

```
svc := sqs.New(sess)

_, 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:    queueURL,
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/SendMessage/SendMessage.go) on GitHub.

## Receiving a Message from a Queue
<a name="sqs-example-receive-mesage"></a>

Create a new Go file named `ReceiveMessage.go`.

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

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the name of the queue and how long the message is hidden from other consumers from the command line.

```
queue := flag.String("q", "", "The name of the queue")
timeout := flag.Int64("t", 5, "How long, in seconds, that the message is hidden from others")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply the name of a queue (-q QUEUE)")
    return
}

if *timeout < 0 {
    *timeout = 0
}

if *timeout > 12*60*60 {
    *timeout = 12 * 60 * 60
}
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call the *GetQueueUrl* function to get the URL of the queue.

```
svc := sqs.New(sess)

urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queue,
})
```

The URL of the queue is in the *QueueUrl* property of the returned object.

```
queueURL := urlResult.QueueUrl
```

Call the *ReceiveMessage* function to get the messages in the queue.

```
msgResult, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
    AttributeNames: []*string{
        aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
    },
    MessageAttributeNames: []*string{
        aws.String(sqs.QueueAttributeNameAll),
    },
    QueueUrl:            queueURL,
    MaxNumberOfMessages: aws.Int64(1),
    VisibilityTimeout:   timeout,
})
```

Print the message handle of the first message in the queue (you need the handle to delete the message).

```
fmt.Println("Message Handle: " + *msgResult.Messages[0].ReceiptHandle)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/ReceiveMessage/ReceiveMessage.go) on GitHub.

## Delete a Message from a Queue
<a name="sqs-example-delete-message"></a>

Create a new Go file named `DeleteMessage.go`.

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

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the name of the queue and the handle for the message from the command line.

```
queue := flag.String("q", "", "The name of the queue")
messageHandle := flag.String("m", "", "The receipt handle of the message")
flag.Parse()

if *queue == "" || *messageHandle == "" {
    fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-m MESSAGE-HANDLE)")
    return
}
```

Initialize a session that the SDK uses to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call the *DeleteMessage* function, passing in the name of the queue and the message handle.

```
svc := sqs.New(sess)

_, err := svc.DeleteMessage(&sqs.DeleteMessageInput{
    QueueUrl:      queueURL,
    ReceiptHandle: messageHandle,
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/DeleteMessage/DeleteMessage.go) on GitHub.

# Managing Visibility Timeout in Amazon SQS Queues
<a name="sqs-example-managing-visibility-timeout"></a>

This AWS SDK for Go example shows you how to:
+ Change visibility timeout with Amazon SQS queues

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/sqs) repository on GitHub.

## Scenario
<a name="sqs-visibility-scenario"></a>

This example manages visibility timeout with Amazon SQS queues. Visibility is the duration, in seconds, while messages are in the queue, but not available to other consumers. It uses these methods of the Amazon SQS client class:
+  [ChangeMessageVisibility](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.ChangeMessageVisibility) 
+  [GetQueueUrl](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.GetQueueUrl) 

## Prerequisites
<a name="sqs-visibility-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with using Amazon SQS visibility timeout. To learn more, see [Visibility Timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) in the Amazon SQS Developer Guide.

## Change the Visibility Timeout
<a name="sqs-example-visibility-timeout"></a>

Create a new Go file named `ChangeMsgVisibility.go`.

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

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the queue name, receipt handle of the message, and visibility duration from the command line. Ensure the visibility is from 0 (zero) seconds to 12 hours.

```
queue := flag.String("q", "", "The name of the queue")
handle := flag.String("h", "", "The receipt handle of the message")
visibility := flag.Int64("v", 30, "The duration, in seconds, that the message is not visible to other consumers")
flag.Parse()

if *queue == "" || *handle == "" {
    fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-h HANDLE)")
    return
}

if *visibility < 0 {
    *visibility = 0
}

if *visibility > 12*60*60 {
    *visibility = 12 * 60 * 60
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials` and the default region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `GetQueueUrl` to retrieve the URL of the queue.

```
svc := sqs.New(sess)

result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queue,
})
```

The URL of the queue is in the `QueueUrl` property of the returned object.

```
queueURL := urlResult.QueueUrl
```

Call `ChangeMessageVisibility` to change the visibility of the messages in the queue.

```
_, err := svc.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{
    ReceiptHandle:     handle,
    QueueUrl:          queueURL,
    VisibilityTimeout: visibility,
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility.go) on GitHub.

# Enabling Long Polling in Amazon SQS Queues
<a name="sqs-example-enable-long-polling"></a>

These AWS SDK for Go examples show you how to:
+ Enable long polling when you create an Amazon SQS queue
+ Enable long polling on an existing Amazon SQS queue
+ Enable long polling when a message is received

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/sqs) repository on GitHub.

## Scenario
<a name="sqs-long-polling-scenario"></a>

Long polling reduces the number of empty responses by allowing Amazon SQS to wait a specified time for a message to become available in the queue before sending a response. Also, long polling eliminates false empty responses by querying all of the servers instead of a sampling of servers. To enable long polling, you must specify a non-zero wait time for received messages. You can do this by setting the `ReceiveMessageWaitTimeSeconds` parameter of a queue or by setting the `WaitTimeSeconds` parameter on a message when it is received.

The code uses these methods of the Amazon SQS client class:
+  [CreateQueue](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.CreateQueue) 
+  [SetQueueAttributes](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.SetQueueAttributes) 
+  [ReceiveMessage](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.ReceiveMessage) 

## Prerequisites
<a name="sqs-long-polling-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with Amazon SQS polling. To learn more, see [Long Polling](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html) in the Amazon SQS Developer Guide.

## Enable Long Polling When Creating a Queue
<a name="sqs-example-create-queue-long-pollling"></a>

This example creates a queue with long polling enabled. If the queue already exists, no error is returned.

Create a new Go file named `CreateLPQueue.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "flag"
    "fmt"
    "strconv"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the queue name and wait time from the command line. Ensure that the wait time is between 0 (zero) and 20 seconds.

```
queue := flag.String("q", "", "The name of the queue")
waitTime := flag.Int("w", 10, "How long, in seconds, to wait for long polling")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply a queue name (-q QUEUE")
    return
}

if *waitTime < 1 {
    *waitTime = 1
}

if *waitTime > 20 {
    *waitTime = 20
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials` and the default AWS Region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `CreateQueue`, passing in the time to wait for messages.

```
svc := sqs.New(sess)

result, err := svc.CreateQueue(&sqs.CreateQueueInput{
    QueueName: queueName,
    Attributes: aws.StringMap(map[string]string{
        "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*waitTime),
    }),
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/CreateLPQueue/CreateLPQueue.go) on GitHub.

## Enable Long Polling on an Existing Queue
<a name="enable-long-polling-on-an-existing-queue"></a>

Create a new Go file named `ConfigureLPQueue.go`.

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

```
import (
    "flag"
    "fmt"
    "strconv"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the queue name and the optional timeout value from the command line. Ensure that the wait time is between 1 and 20 seconds.

```
queue := flag.String("q", "", "The name of the queue")
waitTime := flag.Int("w", 10, "The wait time, in seconds, for long polling")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply a queue name (-q QUEUE")
    return
}

if *waitTime < 1 {
    *waitTime = 1
}

if *waitTime > 20 {
    *waitTime = 20
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials`, and a default AWS Region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Get the URL of the queue.

```
svc := sqs.New(sess)

result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queue,
})
```

The URL is in the QueueUrl property of the returned object.

```
queueURL := result.QueueUrl
```

Update the queue to enable long polling with a call to `SetQueueAttributes`, passing in the queue URL.

```
_, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{
    QueueUrl: queueURL,
    Attributes: aws.StringMap(map[string]string{
        "ReceiveMessageWaitTimeSeconds": strconv.Itoa(aws.IntValue(waitTime)),
    }),
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/ConfigureLPQueue/ConfigureLPQueue.go) on GitHub.

## Enable Long Polling on Message Receipt
<a name="enable-long-polling-on-message-receipt"></a>

Create a new Go file named `ReceiveLPMessage.go`.

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

```
import (
    "flag"
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the queue name and optional visibility and wait time values from the command line. Ensure that the visibility is between 0 (zero) seconds and 12 hours and that the wait time is between 0 and 20 seconds.

```
queue := flag.String("q", "", "The name of the queue")
waitTime := flag.Int64("w", 10, "How long the queue waits for messages")
flag.Parse()

if *queue == "" {
    fmt.Println("You must supply a queue name (-q QUEUE")
    return
}

if *waitTime < 0 {
    *waitTime = 0
}

if *waitTime > 20 {
    *waitTime = 20
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials` and the default AWS Region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `GetQueueUrl` to get the URL of the queue.

```
svc := sqs.New(sess)

result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queue,
})
```

Call `ReceiveMessage` to get the messages, using long polling, from the queue.

```
result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{
    QueueUrl: queueURL,
    AttributeNames: aws.StringSlice([]string{
        "SentTimestamp",
    }),
    MaxNumberOfMessages: aws.Int64(1),
    MessageAttributeNames: aws.StringSlice([]string{
        "All",
    }),
    WaitTimeSeconds: waitTime,
})
```

Display the IDs of the mesages.

```
    fmt.Println("Message IDs:")

    for _, msg := range msgs {
        fmt.Println("    " + *msg.MessageId)
    }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/ReceiveLPMessage/ReceiveLPMessage.go) on GitHub.

# Using Dead Letter Queues in Amazon SQS
<a name="sqs-example-dead-letter-queues"></a>

This AWS SDK for Go example shows you how to configure source Amazon SQS queues that send messages to a dead letter queue.

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/sqs) repository on GitHub.

## Scenario
<a name="sqs-dead-letter-queue-scenario"></a>

A dead letter queue is one that other (source) queues can target for messages that can’t be processed successfully. You can set aside and isolate these messages in the dead letter queue to determine why their processing didn’t succeed. You must individually configure each source queue that sends messages to a dead letter queue. Multiple queues can target a single dead letter queue.

The code uses this method of the Amazon SQS client class:
+  [SetQueueAttributes](https://docs.aws.amazon.com/sdk-for-go/api/service/sqs/#SQS.SetQueueAttributes) 

## Prerequisites
<a name="sqs-dead-letter-queue-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with Amazon SQS dead letter queues. To learn more, see [Using Amazon SQS Dead Letter Queues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) in the Amazon SQS Developer Guide.

## Configure Source Queues
<a name="sqs-example-configure-source-queues"></a>

After you create a queue to act as a dead letter queue, you must configure the other queues that route unprocessed messages to the dead letter queue. To do this, specify a redrive policy that identifies the queue to use as a dead letter queue and the maximum number of receives by individual messages before they are routed to the dead letter queue.

Create a new Go file with the name `DeadLetterQueue.go`.

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

```
import (
    "encoding/json"
    "flag"
    "fmt"
    "strings"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sqs"
)
```

Get the name of the queue and the dead letter queue from the commmand line.

```
    queue := flag.String("q", "", "The name of the queue")
    dlQueue := flag.String("d", "", "The name of the dead-letter queue")
    flag.Parse()

    if *queue == "" || *dlQueue == "" {
        fmt.Println("You must supply the names of the queue (-q QUEUE) and the dead-letter queue (-d DLQUEUE)")
        return
    }
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials` and the default AWS Region from `~/.aws/config`.

```
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
```

Create a service client and call `GetQueueUrl` to get the URL for the queue.

```
svc := sqs.New(sess)

result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{
    QueueName: queue,
})
```

The URL of the queue is in the `QueueUrl` property of the returned object.

```
queueURL := result.QueueUrl
```

Similarly, get the URL of the dead letter queue.

Create the ARN of the dead-letter queue from the URL.

```
parts := strings.Split(*queueURL, "/")
subParts := strings.Split(parts[2], ".")

arn := "arn:aws:" + subParts[0] + ":" + subParts[1] + ":" + parts[3] + ":" + parts[4]
```

Define the redrive policy for the queue.

```
policy := map[string]string{
    "deadLetterTargetArn": *dlQueueARN,
    "maxReceiveCount":     "10",
}
```

Marshal the policy to use as input for the `SetQueueAttributes` call.

```
b, err := json.Marshal(policy)
```

Set the policy on the queue.

```
_, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{
    QueueUrl: queueURL,
    Attributes: map[string]*string{
        sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)),
    },
})
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/sqs/DeadLetterQueue/DeadLetterQueue.go) on GitHub.