

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/).

# AWS SDK for Go Code Examples
<a name="common-examples"></a>

The AWS SDK for Go examples can help you write your own Go applications that use Amazon Web Services. The examples assume you have already set up and configured the SDK (that is, you have 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).

Find the source code for these examples and others in the AWS documentation [code examples repository on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples). To propose a new code example for the AWS documentation team to consider producing, create a new request. The team is looking to produce code examples that cover broader scenarios and use cases, versus simple code snippets that cover only individual API calls. For instructions, see the *Proposing new code examples* section in the [Readme on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples).

**Topics**
+ [SDK Request Examples](using-requests-with-go-sdk.md)
+ [AWS CloudTrail Examples](using-cloudtrail-with-go-sdk.md)
+ [Amazon CloudWatch Examples](using-cloudwatch-with-go-sdk.md)
+ [AWS CodeBuild Examples](using-cb-with-go-sdk.md)
+ [Amazon DynamoDB Examples](using-dynamodb-with-go-sdk.md)
+ [Amazon EC2 Examples](using-ec2-with-go-sdk.md)
+ [Amazon Glacier Examples](using-glacier-with-go-sdk.md)
+ [IAM Examples](using-iam-with-go-sdk.md)
+ [AWS KMS Examples](using-kms-with-go-sdk.md)
+ [AWS Lambda Examples](using-lambda-with-go-sdk.md)
+ [Amazon Polly Examples](using-polly-with-go-sdk.md)
+ [Amazon S3 Examples](using-s3-with-go-sdk.md)
+ [Amazon SES Examples](using-ses-with-go-sdk.md)
+ [Amazon SNS Examples](using-sns-with-go-sdk.md)
+ [Amazon SQS Examples](using-sqs-with-go-sdk.md)

# AWS SDK for Go Request Examples
<a name="using-requests-with-go-sdk"></a>

The AWS SDK for Go examples can help you write your own applications. The examples assume you have already set up and configured the SDK (that is, you have 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).

## Using context.Context with SDK Requests
<a name="using-context-context-with-requests"></a>

In Go 1.7, the `context.Context` type was added to `http.Request`. This type provides an easy way to implement deadlines and cancellations on requests.

To use this pattern with the SDK, call `WithContext` on the `HTTPRequest` field of the SDK’s `request.Request` type, and provide your `Context value`. The following example highlights this process with a timeout on Amazon SQS`ReceiveMessage`.

```
req, resp := svc.ReceiveMessageRequest(params)
req.HTTPRequest = req.HTTPRequest.WithContext(ctx)

err := req.Send()
if err != nil {
    fmt.Println("Got error receiving message:")
    fmt.Println(err.Error())
} else {
    fmt.Println(resp)
}
```

## Using API Field Setters with SDK Requests
<a name="using-api-field-setters"></a>

In addition to setting API parameters by using struct fields, you can also use chainable setters on the API operation parameter fields. This enables you to use a chain of setters to set the fields of the API struct.

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

_, err := svc.PutObject((&s3.PutObjectInput{}).
    SetBucket(*bucket).
    SetKey(*key).
    SetBody(strings.NewReader("object body")), //.
//      SetWebsiteRedirectLocation("https://example.com/something"),
)
```

You can also use this pattern with nested fields in API operation requests.

```
resp, err := svc.UpdateService((&ecs.UpdateServiceInput{}).
    SetService("myService").
    SetDeploymentConfiguration((&ecs.DeploymentConfiguration{}).
        SetMinimumHealthyPercent(80),
    ),
)
```

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

CloudTrail is an AWS service that helps you enable governance, compliance, and operational and risk auditing of your AWS account. Actions taken by a user, role, or an AWS service are recorded as events in CloudTrail. Events include actions taken in the AWS Management Console, AWS Command Line Interface, and AWS SDKs and APIs.

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/cloudtrail) repository on GitHub.

**Topics**
+ [Listing the CloudTrail Trails](cloudtrail-example-describe-trails.md)
+ [Creating a CloudTrail Trail](cloudtrail-example-create-trail.md)
+ [Listing CloudTrail Trail Events](cloudtrail-example-lookup-events.md)
+ [Deleting a CloudTrail Trail](cloudtrail-example-delete-trail.md)

# Listing the CloudTrail Trails
<a name="cloudtrail-example-describe-trails"></a>

This example uses the [DescribeTrails](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.DescribeTrails) operation to list the names of the CloudTrail trails and the bucket in which CloudTrail stores information in the `us-west-2` region.

Choose `Copy` to save the code locally.

Create the file *describe\$1trails.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "fmt"

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

Initialize the session that the SDK uses to load credentials from the shared credentials file `.aws/credentials` in your home folder, and create a new service client.

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

// Create CloudTrail client
svc := cloudtrail.New(sess)
```

Call **DescribeTrails**. If an error occurs, print the error and exit. If no error occurs, loop through the trails, printing the name of each trail and the bucket.

```
resp, err := svc.DescribeTrails(&cloudtrail.DescribeTrailsInput{TrailNameList: nil})
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Found", len(resp.TrailList), "trail(s)")
fmt.Println("")

for _, trail := range resp.TrailList {
    fmt.Println("Trail name:  " + *trail.Name)
    fmt.Println("Bucket name: " + *trail.S3BucketName)
    fmt.Println("")
}
```

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

# Creating a CloudTrail Trail
<a name="cloudtrail-example-create-trail"></a>

This example uses the [CreateTrail](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.CreateTrail) operation to create a CloudTrail trail in the `us-west-2` region. It requires two inputs, the name of the trail and the name of the bucket in which CloudTrail stores information. If the bucket does not have the proper policy, include the **-p** flag to attach the correct policy to the bucket.

Choose `Copy` to save the code locally.

Create the file *create\$1trail.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudtrail"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/sts"

    "encoding/json"
    "flag"
    "fmt"
)
```

Get the names of the trail and bucket, and whether to attach the policy to the bucket. If either the trail name or bucket name is missing, display an error message and exit.

```
trailNamePtr := flag.String("n", "", "The name of the trail")
bucketNamePtr := flag.String("b", "", "the name of the bucket to which the trails are uploaded")
addPolicyPtr := flag.Bool("p", false, "Whether to add the CloudTrail policy to the bucket")

flag.Parse()

if *trailNamePtr == "" || *bucketNamePtr == "" {
    fmt.Println("You must supply a trail name and bucket name.")
    return
}
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `.aws/credentials` in your home folder.

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

If the **-p** flag was specfied, add a policy to the bucket.

```
if *addPolicyPtr {
    svc := sts.New(sess)
    input := &sts.GetCallerIdentityInput{}

    result, err := svc.GetCallerIdentity(input)
    if err != nil {
        fmt.Println("Got error snarfing caller identity:")
        fmt.Println(err.Error())
        return
    }

    accountID := aws.StringValue(result.Account)

    s3Policy := map[string]interface{}{
        "Version": "2012-10-17",		 	 	 
        "Statement": []map[string]interface{}{
            {
                "Sid":    "AWSCloudTrailAclCheck20150319",
                "Effect": "Allow",
                "Principal": map[string]interface{}{
                    "Service": "cloudtrail.amazonaws.com",
                },
                "Action":   "s3:GetBucketAcl",
                "Resource": "arn:aws:s3:::" + *bucketNamePtr,
            },
            {
                "Sid":    "AWSCloudTrailWrite20150319",
                "Effect": "Allow",
                "Principal": map[string]interface{}{
                    "Service": "cloudtrail.amazonaws.com",
                },
                "Action":   "s3:PutObject",
                "Resource": "arn:aws:s3:::" + *bucketNamePtr + "/AWSLogs/" + accountID + "/*",
                "Condition": map[string]interface{}{
                    "StringEquals": map[string]interface{}{
                        "s3:x-amz-acl": "bucket-owner-full-control",
                    },
                },
            },
        },
    }

    policy, err := json.Marshal(s3Policy)
    if err != nil {
        fmt.Println("Error marshalling request")
        return
    }

    // Create S3 service
    s3Svc := s3.New(sess)

    // Now set the policy on the bucket
    _, err = s3Svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
        Bucket: aws.String(*bucketNamePtr),
        Policy: aws.String(string(policy)),
    })
    if err != nil {
        fmt.Print("Got error adding bucket policy:")
        fmt.Print(err.Error())
        return
    }

    fmt.Printf("Successfully set bucket %q's policy\n", *bucketNamePtr)
}
```

Create the CloudTrail client, the input for **CreateTrail**, and call **CreateTrail**. If an error occurs, print the error and exit. If no error occurs, print a success message.

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

input := &cloudtrail.CreateTrailInput{
    Name:         aws.String(*trailNamePtr),
    S3BucketName: aws.String(*bucketNamePtr),
}

_, err := svc.CreateTrail(input)
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Created the trail", *trailNamePtr, "for bucket", *bucketNamePtr)
```

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

# Listing CloudTrail Trail Events
<a name="cloudtrail-example-lookup-events"></a>

This example uses the [LookupEvents](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.LookupEvents) operation to list the CloudTrail trail events in the `us-west-2` region.

Choose `Copy` to save the code locally.

Create the file *lookup\$1events.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudtrail"

    "flag"
    "fmt"
    "time"
)
```

Get the name of the trail. If the trail name is missing, display an error message and exit.

```
trailNamePtr := flag.String("n", "", "The name of the trail")

flag.Parse()

if *trailNamePtr == "" {
    fmt.Println("You must supply a trail name")
    return
}
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `.aws/credentials` in your home folder, and create a new service client.

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

Create the CloudTrail client, and the input for and call **LookupEvents**. If an error occurs, print the error and exit. If no error occurs, loop through the events, printing information about each event.

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

input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())}

resp, err := svc.LookupEvents(input)
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Found", len(resp.Events), "events before now")
fmt.Println("")

for _, event := range resp.Events {
    fmt.Println("Event:")
    fmt.Println(aws.StringValue(event.CloudTrailEvent))
    fmt.Println("")
    fmt.Println("Name    ", aws.StringValue(event.EventName))
    fmt.Println("ID:     ", aws.StringValue(event.EventId))
    fmt.Println("Time:   ", aws.TimeValue(event.EventTime))
    fmt.Println("User:   ", aws.StringValue(event.Username))

    fmt.Println("Resources:")

    for _, resource := range event.Resources {
        fmt.Println("  Name:", aws.StringValue(resource.ResourceName))
        fmt.Println("  Type:", aws.StringValue(resource.ResourceType))
    }

    fmt.Println("")
```

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

# Deleting a CloudTrail Trail
<a name="cloudtrail-example-delete-trail"></a>

This example uses the [DeleteTrail](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudtrail/#CloudTrail.DeleteTrail) operation to delete a CloudTrail trail in the `us-west-2` region. It requires one input, the name of the trail.

Choose `Copy` to save the code locally.

Create the file *delete\$1trail.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudtrail"

    "flag"
    "fmt"
)
```

Get the name of the trail. If the trail name is missing, display an error message and exit.

```
trailNamePtr := flag.String("n", "", "The name of the trail to delete")

flag.Parse()

if *trailNamePtr == "" {
    fmt.Println("You must supply a trail name")
    return
}
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `.aws/credentials` in your home folder and create the client.

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

Create a CloudTrail client and call **DeleteTrail** with the trail name. If an error occurs, print the error and exit. If no error occurs, print a success message.

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

_, err := svc.DeleteTrail(&cloudtrail.DeleteTrailInput{Name: aws.String(*trailNamePtr)})
if err != nil {
    fmt.Println("Got error calling CreateTrail:")
    fmt.Println(err.Error())
    return
}

fmt.Println("Successfully deleted trail", *trailNamePtr)
```

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

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

Amazon CloudWatch is a web service that monitors your AWS resources and the applications you run on AWS in real time. You can use CloudWatch to collect and track metrics, which are variables you can measure for your resources and applications. CloudWatch alarms send notifications or automatically make changes to the resources you are monitoring based on rules that you define.

The AWS SDK for Go examples show you how to integrate CloudWatch into your Go applications. The examples assume you have already set up and configured the SDK (that is, you have 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/cloudwatch) repository on GitHub.

**Topics**
+ [Describing CloudWatch Alarms](cw-example-describing-alarms.md)
+ [Using Alarms and Alarm Actions in CloudWatch](cw-example-using-alarm-actions.md)
+ [Getting Metrics from CloudWatch](cw-example-getting-metrics.md)
+ [Sending Events to Amazon CloudWatch Events](cw-example-sending-events.md)
+ [Getting Log Events from CloudWatch](cw-example-getting-log-events.md)

# Describing CloudWatch Alarms
<a name="cw-example-describing-alarms"></a>

This example shows you how to retrieve basic information that describes your CloudWatch alarms.

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/cloudwatch) repository on GitHub.

## Scenario
<a name="cw-describe-alarms-scenario"></a>

An alarm watches a single metric over a time period you specify. The alarm performs one or more actions based on the value of the metric relative to a given threshold over a number of time periods.

In this example, Go code is used to describe alarms in CloudWatch. The code uses the AWS SDK for Go to describe alarms by using this method of the `AWS.CloudWatch` client class:
+  [DescribeAlarms](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.DescribeAlarms) 

## Prerequisites
<a name="cw-describe-alarms-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch alarms. To learn more, see [Creating Amazon CloudWatch Alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html) in the Amazon CloudWatch User Guide.

## Describe Alarms
<a name="cw-example-alarms"></a>

Choose **Copy** to save the code locally.

Create the file `describe_alarms.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

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

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

Call `DescribeAlarms`, and print the results.

```
resp, err := svc.DescribeAlarms(nil)
for _, alarm := range resp.MetricAlarms {
    fmt.Println(*alarm.AlarmName)
}
```

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

# Using Alarms and Alarm Actions in CloudWatch
<a name="cw-example-using-alarm-actions"></a>

These Go examples show you how to change the state of your Amazon EC2 instances automatically based on a CloudWatch alarm, as follows:
+ Creating and enabling actions on an alarm
+ Disabling actions on an alarm

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/cloudwatch) repository on GitHub.

## Scenario
<a name="cw-create-alarm-actions-scenario"></a>

You can use alarm actions to create alarms that automatically stop, terminate, reboot, or recover your Amazon EC2 instances. You can use the stop or terminate actions when you no longer need an instance to be running. You can use the reboot and recover actions to automatically reboot the instance.

In this example, Go code is used to define an alarm action in CloudWatch that triggers the reboot of an Amazon EC2 instance. The code uses the AWS SDK for Go to manage instances by using these methods of [PutMetricAlarm](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch) type:
+  [PutMetricAlarm](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.PutMetricAlarm) 
+  [EnableAlarmActions](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.EnableAlarmActions) 
+  [DisableAlarmActions](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.DisableAlarmActions) 

## Prerequisites
<a name="cw-create-alarm-actions-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch alarm actions. To learn more, see [Create Alarms to Stop, Terminate, Reboot, or Recover an Instance](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html) in the Amazon CloudWatch User Guide.

## Create and Enable Actions on an Alarm
<a name="cw-example-alarm-actions"></a>

Choose **Copy** to save the code locally.

Create the file `create_enable_alarms.go`.

Import packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Get an instance name, value, and alarm name.

```
if len(os.Args) != 4 {
    fmt.Println("You must supply an instance name, value, and alarm name")
    os.Exit(1)
}

instance := os.Args[1]
value := os.Args[2]
name := os.Args[3]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

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

// Create new CloudWatch client.
svc := cloudwatch.New(sess)
```

Create a metric alarm that reboots an instance if its CPU utilization is greater than 70 percent.

```
_, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{
    AlarmName:          aws.String(name),
    ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold),
    EvaluationPeriods:  aws.Int64(1),
    MetricName:         aws.String("CPUUtilization"),
    Namespace:          aws.String("AWS/EC2"),
    Period:             aws.Int64(60),
    Statistic:          aws.String(cloudwatch.StatisticAverage),
    Threshold:          aws.Float64(70.0),
    ActionsEnabled:     aws.Bool(true),
    AlarmDescription:   aws.String("Alarm when server CPU exceeds 70%"),
    Unit:               aws.String(cloudwatch.StandardUnitSeconds),

    // This is apart of the default workflow actions. This one will reboot the instance, if the
    // alarm is triggered.
    AlarmActions: []*string{
        aws.String(fmt.Sprintf("arn:aws:swf:us-east-1:%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", instance)),
    },
    Dimensions: []*cloudwatch.Dimension{
        {
            Name:  aws.String("InstanceId"),
            Value: aws.String(value),
        },
    },
})
```

Call `EnableAlarmActions` with the new alarm for the instance, and display a message.

```
result, err := svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{
    AlarmNames: []*string{
        aws.String(name),
    },
})
fmt.Println("Alarm action enabled", result)
```

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

## Disable Actions on an Alarm
<a name="disable-actions-on-an-alarm"></a>

Choose **Copy** to save the code locally.

Create the file `disable_alarm.go`.

Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Get the name of the alarm from the command line.

```
if len(os.Args) != 2 {
    fmt.Println("You must supply an alarm name")
    os.Exit(1)
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

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

// Create new CloudWatch client.
svc := cloudwatch.New(sess)
```

Call `DisableAlarmActions` to disable the actions for this alarm and display a message.

```
// Disable the alarm.
_, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{
    AlarmNames: []*string{
        aws.String(name),
    },
})
fmt.Println("Success")
```

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

# Getting Metrics from CloudWatch
<a name="cw-example-getting-metrics"></a>

These Go examples show you how to retrieve a list of published CloudWatch metrics and publish data points to CloudWatch metrics with the AWS SDK for Go, as follows:
+ Listing metrics
+ Submitting custom metrics

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/cloudwatch) repository on GitHub.

## Scenario
<a name="cw-get-metrics-scenario"></a>

Metrics are data about the performance of your systems. You can enable detailed monitoring of some resources, such as your Amazon EC2 instances, or your own application metrics.

In this example, Go code is used to get metrics from CloudWatch and to send events to CloudWatch Events. The code uses the AWS SDK for Go to get metrics from CloudWatch by using these methods of the CloudWatch type:
+  [ListMetrics](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.ListMetrics) 
+  [PutMetricData](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatch/#CloudWatch.PutMetricData) 

## Prerequisites
<a name="cw-get-metrics-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch metrics. To learn more, see [Using Amazon CloudWatch Metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html) in the Amazon CloudWatch User Guide.

## List Metrics
<a name="cw-example-list-metrics"></a>

Choose **Copy** to save the code locally.

Create the file `listing_metrics.go`.

Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
    "os"
)
```

Get the metric name, namespace, and dimension name from the command line.

```
if len(os.Args) != 4 {
    fmt.Println("You must supply a metric name, namespace, and dimension name")
    os.Exit(1)
}

metric := os.Args[1]
namespace := os.Args[2]
dimension := os.Args[3]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

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

// Create CloudWatch client
svc := cloudwatch.New(sess)
```

Call `ListMetrics`, supplying the metric name, namespace, and dimension name. Print the metrics returned in the result.

```
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
    MetricName: aws.String(metric),
    Namespace:  aws.String(namespace),
    Dimensions: []*cloudwatch.DimensionFilter{
        &cloudwatch.DimensionFilter{
            Name: aws.String(dimension),
        },
    },
})
fmt.Println("Metrics", result.Metrics)
```

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

## Submit Custom Metrics
<a name="cw-example-custom-metrics"></a>

Choose **Copy** to save the code locally.

Create the file `custom_metrics.go`.

Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatch"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch client.

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

// Create new cloudwatch client.
svc := cloudwatch.New(sess)
```

Call `PutMetricData` with the the custom namespace “Site/Traffic”. The namespace has two custom dimensions: “SiteName” and “PageURL”. “SiteName” has the value “example.com”, the “UniqueVisitors” value 5885 and the “UniqueVisits” value 8628. “PageURL” has the value “my-page.html”, and a “PageViews” value 18057.

```
_, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{
    Namespace: aws.String("Site/Traffic"),
    MetricData: []*cloudwatch.MetricDatum{
        &cloudwatch.MetricDatum{
            MetricName: aws.String("UniqueVisitors"),
            Unit:       aws.String("Count"),
            Value:      aws.Float64(5885.0),
            Dimensions: []*cloudwatch.Dimension{
                &cloudwatch.Dimension{
                    Name:  aws.String("SiteName"),
                    Value: aws.String("example.com"),
                },
            },
        },
        &cloudwatch.MetricDatum{
            MetricName: aws.String("UniqueVisits"),
            Unit:       aws.String("Count"),
            Value:      aws.Float64(8628.0),
            Dimensions: []*cloudwatch.Dimension{
                &cloudwatch.Dimension{
                    Name:  aws.String("SiteName"),
                    Value: aws.String("example.com"),
                },
            },
        },
        &cloudwatch.MetricDatum{
            MetricName: aws.String("PageViews"),
            Unit:       aws.String("Count"),
            Value:      aws.Float64(18057.0),
            Dimensions: []*cloudwatch.Dimension{
                &cloudwatch.Dimension{
                    Name:  aws.String("PageURL"),
                    Value: aws.String("my-page.html"),
                },
            },
        },
    },
})
```

If there are any errors, print them out, otherwise list some information about the custom metrics.

```
if err != nil {
    fmt.Println("Error adding metrics:", err.Error())
    return
}

// Get information about metrics
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
    Namespace: aws.String("Site/Traffic"),
})
if err != nil {
    fmt.Println("Error getting metrics:", err.Error())
    return
}

for _, metric := range result.Metrics {
    fmt.Println(*metric.MetricName)

    for _, dim := range metric.Dimensions {
        fmt.Println(*dim.Name + ":", *dim.Value)
        fmt.Println()
    }
}
```

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

# Sending Events to Amazon CloudWatch Events
<a name="cw-example-sending-events"></a>

These Go examples show you how to use the AWS SDK for Go to:
+ Create and update a rule used to trigger an event
+ Define one or more targets to respond to an event
+ Send events that are matched to targets for handling

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/cloudwatch) repository on GitHub.

## Scenario
<a name="cw-get-sending-events-scenario"></a>

CloudWatch Events delivers a near real-time stream of system events that describe changes in AWS resources to any of various targets. Using simple rules, you can match events and route them to one or more target functions or streams.

In these examples, Go code is used to send events to CloudWatch Events. The code uses the AWS SDK for Go to manage instances by using these methods of the [CloudWatchEvents](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents) type:
+  [PutRule](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents.PutRule) 
+  [PutTargets](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents.PutTargets) 
+  [PutEvents](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#CloudWatchEvents.PutEvents) 

## Prerequisites
<a name="cw-sending-events-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with CloudWatch Events. To learn more, see [Adding Events with PutEvents](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html) in the Amazon CloudWatch Events User Guide.

## Tasks Before You Start
<a name="tasks-before-you-start"></a>

To set up and run this example, you must first complete these tasks:

1. Create a Lambda function using the hello-world blueprint to serve as the target for events. To learn how, see [Step 1: Create an AWS Lambda function](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/LogEC2InstanceState.html) in the CloudWatch Events User Guide.

1. Create an IAM role whose policy grants permission to CloudWatch Events and that includes `events.amazonaws.com` as a trusted entity. For more information about creating an IAM role, see [Creating a Role to Delegate Permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the IAM User Guide.

   Use the following role policy when creating the IAM role.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Sid": "CloudWatchEventsFullAccess",
         "Effect": "Allow",
         "Action": "events:*",
         "Resource": "*"
      },
      {
         "Sid": "IAMPassRoleForCloudWatchEvents",
         "Effect": "Allow",
         "Action": "iam:PassRole",
         "Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
      }
   ]
}
```

------

Use the following trust relationship when creating the IAM role.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Principal": {
            "Service": "events.amazonaws.com"
         },
         "Action": "sts:AssumeRole"
      }
   ]
}
```

------

## Create a Scheduled Rule
<a name="cw-example-scheduled-rule"></a>

Choose **Copy** to save the code locally.

Create the file `events_schedule_rule.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchevents"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch Events client.

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

// Create the cloudwatch events client
svc := cloudwatchevents.New(sess)
```

Call `PutRule`, supplying a name, `DEMO_EVENT`, ARN of the IAM role you created, `IAM_ROLE_ARN`, and an expression defining the schedule. Finally, display the ARN of the rule.

```
result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{
    Name:               aws.String("DEMO_EVENT"),
    RoleArn:            aws.String("IAM_ROLE_ARN"),
    ScheduleExpression: aws.String("rate(5 minutes)"),
})
fmt.Println("Rule ARN:", result.RuleArn)
```

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

## Add a Lambda Function Target
<a name="add-a-lambda-function-target"></a>

Choose **Copy** to save the code locally.

Create the file `events_put_targets.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchevents"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a new CloudWatch Events client.

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

// Create the cloudwatch events client
svc := cloudwatchevents.New(sess)
```

Call `PutTargets`, supplying a name for the rule, `DEMO_EVENT`. For the target, specify the ARN of the Lambda function you created, `LAMBDA_FUNCTION_ARN`, and the ID of the rule, `myCloudWatchEventsTarget`. Print any errors, or a success message with any targets that failed.

```
result, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{
    Rule: aws.String("DEMO_EVENT"),
    Targets: []*cloudwatchevents.Target{
        &cloudwatchevents.Target{
            Arn: aws.String("LAMBDA_FUNCTION_ARN"),
            Id:  aws.String("myCloudWatchEventsTarget"),
        },
    },
})
fmt.Println("Success", result)
```

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

## Send Events
<a name="send-events"></a>

Choose **Copy** to save the code locally.

Create the file `events_put_events.go`. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/cloudwatchevents"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create a CloudWatch Events client.

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

// Create the cloudwatch events client
svc := cloudwatchevents.New(sess)
```

Call `PutEvents`, supplying key-name value pairs in the `Details` field, and specifying the ARN of the Lambda function you created, `RESOURCE_ARN`. See [PutEventsRequestEntry](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudwatchevents/#PutEventsRequestEntry) for a description of the fields. Finally, display the ingested events.

```
result, err := svc.PutEvents(&cloudwatchevents.PutEventsInput{
    Entries: []*cloudwatchevents.PutEventsRequestEntry{
        &cloudwatchevents.PutEventsRequestEntry{
            Detail:     aws.String("{ \"key1\": \"value1\", \"key2\": \"value2\" }"),
            DetailType: aws.String("appRequestSubmitted"),
            Resources: []*string{
                aws.String("RESOURCE_ARN"),
            },
            Source: aws.String("com.company.myapp"),
        },
    },
})
fmt.Println("Ingested events:", result.Entries)
```

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

# Getting Log Events from CloudWatch
<a name="cw-example-getting-log-events"></a>

The following example lists up to 100 of the latest events for a log group’s log stream. Replace LOG-GROUP-NAME with the name of the CloudWatch log group and LOG-STREAM-NAME with the name of the log stream for the log group.

```
package main

import (
    "flag"
    "fmt"

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

// GetLogEvents retrieves CloudWatchLog events.
// Inputs:
//     sess is the current session, which provides configuration for the SDK's service clients
//     limit is the maximum number of log events to retrieve
//     logGroupName is the name of the log group
//     logStreamName is the name of the log stream
// Output:
//     If success, a GetLogEventsOutput object containing the events and nil
//     Otherwise, nil and an error from the call to GetLogEvents
func GetLogEvents(sess *session.Session, limit *int64, logGroupName *string, logStreamName *string) (*cloudwatchlogs.GetLogEventsOutput, error) {
    svc := cloudwatchlogs.New(sess)

    resp, err := svc.GetLogEvents(&cloudwatchlogs.GetLogEventsInput{
        Limit:         limit,
        LogGroupName:  logGroupName,
        LogStreamName: logStreamName,
    })
    if err != nil {
        return nil, err
    }

    return resp, nil
}

func main() {
    limit := flag.Int64("l", 100, "The maximum number of events to retrieve")
    logGroupName := flag.String("g", "", "The name of the log group")
    logStreamName := flag.String("s", "", "The name of the log stream")
    flag.Parse()

    if *logGroupName == "" || *logStreamName == "" {
        fmt.Println("You must supply a log group name (-g LOG-GROUP) and log stream name (-s LOG-STREAM)")
        return
    }

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

    resp, err := GetLogEvents(sess, limit, logGroupName, logStreamName)
    if err != nil {
        fmt.Println("Got error getting log events:")
        fmt.Println(err)
        return
    }

    fmt.Println("Event messages for stream " + *logStreamName + " in log group  " + *logGroupName)

    gotToken := ""
    nextToken := ""

    for _, event := range resp.Events {
        gotToken = nextToken
        nextToken = *resp.NextForwardToken

        if gotToken == nextToken {
            break
        }

        fmt.Println("  ", *event.Message)
    }
}
```

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

CodeBuild is a fully managed build service that compiles source code, runs tests, and produces software packages that are ready to deploy. The AWS SDK for Go examples can integrate AWS CodeBuild 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/codebuild) repository on GitHub.

**Topics**
+ [Getting Information about All AWS CodeBuild Projects](cb-example-list-projects.md)
+ [Building an AWS CodeBuild Project](cb-example-build-project.md)
+ [Listing Your AWS CodeBuild Project Builds](cb-example-list-builds.md)

# Getting Information about All AWS CodeBuild Projects
<a name="cb-example-list-projects"></a>

The following example lists the names of up to 100 of your AWS CodeBuild projects.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/codebuild"
    "fmt"
    "os"
)

// Lists a CodeBuild projects in the region configured in the shared config
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create CodeBuild service client
    svc := codebuild.New(sess)

    // Get the list of projects
    result, err := svc.ListProjects(
        &codebuild.ListProjectsInput{
            SortBy:    aws.String("NAME"),
            SortOrder: aws.String("ASCENDING", )})

    if err != nil {
        fmt.Println("Got error listing projects: ", err)
        os.Exit(1)
    }

    for _, p := range result.Projects {
        fmt.Println(*p)
    }
}
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/codebuild/cb_list_projects.go) on GitHub.

# Building an AWS CodeBuild Project
<a name="cb-example-build-project"></a>

The following example builds the AWS CodeBuild project specified on the command line. If no command-line argument is supplied, it emits an error and quits.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/codebuild"
    "fmt"
    "os"
)

// Builds a CodeBuild project in the region configured in the shared config
func main() {
    // Requires one argument, the name of the project.
    if len(os.Args) != 2 {
        fmt.Println("Project name required!")
        os.Exit(1)
    }

    project := os.Args[1]

    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create CodeBuild service client
    svc := codebuild.New(sess)

    // Build the project
    _, err = svc.StartBuild(&codebuild.StartBuildInput{ProjectName: aws.String(project)})
    if err != nil {
        fmt.Println("Got error building project: ", err)
        os.Exit(1)
    }

    fmt.Printf("Started build for project %q\n", project)
}
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/codebuild/cb_build_project.go) on GitHub.

# Listing Your AWS CodeBuild Project Builds
<a name="cb-example-list-builds"></a>

The following example displays information about your AWS CodeBuild project builds, including the name of the project, when the build started, and how long each phase of the build took, in seconds.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/codebuild"
    "fmt"
    "os"
)

// Lists the CodeBuild builds for all projects in the region configured in the shared config
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create CodeBuild service client
    svc := codebuild.New(sess)

    // Get the list of builds
    names, err := svc.ListBuilds(&codebuild.ListBuildsInput{SortOrder: aws.String("ASCENDING")})

    if err != nil {
        fmt.Println("Got error listing builds: ", err)
        os.Exit(1)
    }

    // Get information about each build
    builds, err := svc.BatchGetBuilds(&codebuild.BatchGetBuildsInput{Ids: names.Ids})

    if err != nil {
        fmt.Println("Got error getting builds: ", err)
        os.Exit(1)
    }

    for _, build := range builds.Builds {
        fmt.Printf("Project: %s\n", aws.StringValue(build.ProjectName))
        fmt.Printf("Phase:   %s\n", aws.StringValue(build.CurrentPhase))
        fmt.Printf("Status:  %s\n", aws.StringValue(build.BuildStatus))
        fmt.Println("")
    }
}
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/codebuild/cb_list_builds.go) on GitHub.

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

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. The AWS SDK for Go examples can integrate Amazon DynamoDB into your Go applications. The examples assume you have already set up and configured the SDK (that is, you have 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).

The topic also provides a link to a downloadable version of DynamoDB, which includes an interactive web interface so you can experiment with DynamoDB offline.

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/dynamodb) repository on GitHub.

**Topics**
+ [Listing all Amazon DynamoDB Tables](dynamo-example-list-tables.md)
+ [Creating an Amazon DynamoDB Table](dynamo-example-create-table.md)
+ [Creating an Amazon DynamoDB Table Item](dynamo-example-create-table-item.md)
+ [Creating Amazon DynamoDB Table Items from a JSON File](dynamo-example-load-table-items-from-json.md)
+ [Reading an Amazon DynamoDB Table Item](dynamo-example-read-table-item.md)
+ [Getting Amazon DynamoDB Table Items Using Expression Builder](dynamo-example-scan-table-item.md)
+ [Updating an Amazon DynamoDB Table Item](dynamo-example-update-table-item.md)
+ [Deleting an Amazon DynamoDB Table Item](dynamo-example-delete-table-item.md)

# Listing all Amazon DynamoDB Tables
<a name="dynamo-example-list-tables"></a>

The following example uses the DynamoDB [ListTables](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.ListTables) operation to list all of the tables in your default region.

Create the file *DynamoDBListTables.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials` and region from the shared configuration file `~/.aws/config` and create a new DynamoDB service client.

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Call **ListTables**. If an error occurs, print the error and exit. If no error occurs, loop through the tables, printing the name of each table.

```
// create the input configuration instance
input := &dynamodb.ListTablesInput{}

fmt.Printf("Tables:\n")

for {
    // Get the list of tables
    result, err := svc.ListTables(input)
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case dynamodb.ErrCodeInternalServerError:
                fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            fmt.Println(err.Error())
        }
        return
    }

    for _, n := range result.TableNames {
        fmt.Println(*n)
    }

    // assign the last read tablename as the start for our next call to the ListTables function
    // the maximum number of table names returned in a call is 100 (default), which requires us to make
    // multiple calls to the ListTables function to retrieve all table names
    input.ExclusiveStartTableName = result.LastEvaluatedTableName

    if result.LastEvaluatedTableName == nil {
        break
    }
}
```

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

# Creating an Amazon DynamoDB Table
<a name="dynamo-example-create-table"></a>

The following example uses the DynamoDB [CreateTable](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.CreateTable) operation to create the table **Music** your default region.

Create the file *DynamoDBCreateTable.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
    "log"
)
```

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

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Call **CreateTable**. If an error occurs, print the error and exit. If no error occurs, print an message that the table was created.

```
// Create table Movies
tableName := "Movies"

input := &dynamodb.CreateTableInput{
    AttributeDefinitions: []*dynamodb.AttributeDefinition{
        {
            AttributeName: aws.String("Year"),
            AttributeType: aws.String("N"),
        },
        {
            AttributeName: aws.String("Title"),
            AttributeType: aws.String("S"),
        },
    },
    KeySchema: []*dynamodb.KeySchemaElement{
        {
            AttributeName: aws.String("Year"),
            KeyType:       aws.String("HASH"),
        },
        {
            AttributeName: aws.String("Title"),
            KeyType:       aws.String("RANGE"),
        },
    },
    ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
        ReadCapacityUnits:  aws.Int64(10),
        WriteCapacityUnits: aws.Int64(10),
    },
    TableName: aws.String(tableName),
}

_, err := svc.CreateTable(input)
if err != nil {
    log.Fatalf("Got error calling CreateTable: %s", err)
}

fmt.Println("Created the table", tableName)
```

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

# Creating an Amazon DynamoDB Table Item
<a name="dynamo-example-create-table-item"></a>

The following example uses the DynamoDB [PutItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.PutItem) operation to create the table item with the `year` **2015** and `title` **The Big New Movie** in the `Movies` table in your default region.

Create the file *DynamoDBCreateItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

    "fmt"
    "log"
    "strconv"
)
```

Create the data structure we use to containing the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

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

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Create a struct with the movie data and marshall that data into a map of **AttributeValue** objects.

```
item := Item{
    Year:   2015,
    Title:  "The Big New Movie",
    Plot:   "Nothing happens at all.",
    Rating: 0.0,
}

av, err := dynamodbattribute.MarshalMap(item)
if err != nil {
    log.Fatalf("Got error marshalling new movie item: %s", err)
}
```

Create the input for **PutItem** and call it. If an error occurs, print the error and exit. If no error occurs, print an message that the item was added to the table.

```
// Create item in table Movies
tableName := "Movies"

input := &dynamodb.PutItemInput{
    Item:      av,
    TableName: aws.String(tableName),
}

_, err = svc.PutItem(input)
if err != nil {
    log.Fatalf("Got error calling PutItem: %s", err)
}

year := strconv.Itoa(item.Year)

fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName)
```

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

# Creating Amazon DynamoDB Table Items from a JSON File
<a name="dynamo-example-load-table-items-from-json"></a>

The following example uses the DynamoDB [PutItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.PutItem) operation in a loop to create the items defined in *movie\$1data.json* file in the `Movies` table in your default region.

Create the file *DynamoDBLoadItems.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

    "encoding/json"
    "fmt"
    "log"
    "io/ioutil"
    "strconv"
)
```

Create the data structure we use to contain the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

Create a function to get the table items from the JSON file.

```
// Get table items from JSON file
func getItems() []Item {
    raw, err := ioutil.ReadFile("./.movie_data.json")
    if err != nil {
        log.Fatalf("Got error reading file: %s", err)
    }

    var items []Item
    json.Unmarshal(raw, &items)
    return items
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials` and region from the shared configuration file `~/.aws/config` and create a new DynamoDB service client.

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Call **getItems** to get the items. Loop through each item, marshall that data into a map of **AttributeValue** objects, add the item to the `Movies` table, and print out the title and year of the movie added to the table.

```
// Get table items from .movie_data.json
items := getItems()

// Add each item to Movies table:
tableName := "Movies"

for _, item := range items {
    av, err := dynamodbattribute.MarshalMap(item)
    if err != nil {
        log.Fatalf("Got error marshalling map: %s", err)
    }

    // Create item in table Movies
    input := &dynamodb.PutItemInput{
        Item:      av,
        TableName: aws.String(tableName),
    }

    _, err = svc.PutItem(input)
    if err != nil {
        log.Fatalf("Got error calling PutItem: %s", err)
    }

    year := strconv.Itoa(item.Year)

    fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBLoadItems.go) and a [sample JSON file](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/.movie_data.json) on GitHub.

# Reading an Amazon DynamoDB Table Item
<a name="dynamo-example-read-table-item"></a>

The following example uses the DynamoDB [GetItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.GetItem) operation to retrieve information about the item with the `year` **2015** and `title` **The Big New Movie** in the `movies` table in your default region.

Create the file *DynamoDBReadItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

    "fmt"
    "log"
)
```

Create the data structure we use to contain the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials` and region from the shared configuration file `~/.aws/config` and create a new DynamoDB service client.

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Call **GetItem** to get the item from the table. If we encounter an error, print the error message. Otherwise, display information about the item.

```
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"

result, err := svc.GetItem(&dynamodb.GetItemInput{
    TableName: aws.String(tableName),
    Key: map[string]*dynamodb.AttributeValue{
        "Year": {
            N: aws.String(movieYear),
        },
        "Title": {
            S: aws.String(movieName),
        },
    },
})
if err != nil {
    log.Fatalf("Got error calling GetItem: %s", err)
}
```

If an item was returned, unmarshall the return value and display the year, title, plot, and rating.

```
if result.Item == nil {
    msg := "Could not find '" + *title + "'"
    return nil, errors.New(msg)
}
    
item := Item{}

err = dynamodbattribute.UnmarshalMap(result.Item, &item)
if err != nil {
    panic(fmt.Sprintf("Failed to unmarshal Record, %v", err))
}

fmt.Println("Found item:")
fmt.Println("Year:  ", item.Year)
fmt.Println("Title: ", item.Title)
fmt.Println("Plot:  ", item.Plot)
fmt.Println("Rating:", item.Rating)
```

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

# Getting Amazon DynamoDB Table Items Using Expression Builder
<a name="dynamo-example-scan-table-item"></a>

The following example uses the DynamoDB [Scan](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.Scan) operation to get items with a `rating` greater than **4.0** in the `year` **2013** in the `Movies` table in your default region.

The example uses the [Expression Builder](https://aws.amazon.com/blogs/developer/introducing-amazon-dynamodb-expression-builder-in-the-aws-sdk-for-go/) package released in version 1.11.0 of the AWS SDK for Go in September 2017.

Create the file *DynamoDBScanItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
    "github.com/aws/aws-sdk-go/service/dynamodb/expression"

    "fmt"
    "log"
)
```

Create the data structure we use to contain the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials` and region from the shared configuration file `~/.aws/config` and create a new DynamoDB service client.

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Create variables for the minimum rating and year for the table items to retrieve.

```
tableName := "Movies"
minRating := 4.0
year := 2013
```

Create the expression defining the year for which we filter the table items to retrieve, and the projection so we get the title, year, and rating for each retrieved item. Then build the expression.

```
// Create the Expression to fill the input struct with.
// Get all movies in that year; we'll pull out those with a higher rating later
filt := expression.Name("Year").Equal(expression.Value(year))

// Or we could get by ratings and pull out those with the right year later
//    filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating))

// Get back the title, year, and rating
proj := expression.NamesList(expression.Name("Title"), expression.Name("Year"), expression.Name("Rating"))

expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build()
if err != nil {
    log.Fatalf("Got error building expression: %s", err)
}
```

Create the inputs for and call **Scan** to retrieve the items from the table (the movies made in 2013).

```
// Build the query input parameters
params := &dynamodb.ScanInput{
    ExpressionAttributeNames:  expr.Names(),
    ExpressionAttributeValues: expr.Values(),
    FilterExpression:          expr.Filter(),
    ProjectionExpression:      expr.Projection(),
    TableName:                 aws.String(tableName),
}

// Make the DynamoDB Query API call
result, err := svc.Scan(params)
if err != nil {
    log.Fatalf("Query API call failed: %s", err)
}
```

Loop through the movies from 2013 and display the title and rating for those where the rating is greater than 4.0

```
numItems := 0

for _, i := range result.Items {
    item := Item{}

    err = dynamodbattribute.UnmarshalMap(i, &item)

    if err != nil {
        log.Fatalf("Got error unmarshalling: %s", err)
    }

    // Which ones had a higher rating than minimum?
    if item.Rating > minRating {
        // Or it we had filtered by rating previously:
        //   if item.Year == year {
        numItems++

        fmt.Println("Title: ", item.Title)
        fmt.Println("Rating:", item.Rating)
        fmt.Println()
    }
}

fmt.Println("Found", numItems, "movie(s) with a rating above", minRating, "in", year)
```

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

# Updating an Amazon DynamoDB Table Item
<a name="dynamo-example-update-table-item"></a>

The following example uses the DynamoDB [UpdateItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.UpdateItem) operation to update the rating to **0.5** for the item with the `year` **2015** and `title` **The Big New Movie** in the `Movies` table in your default region.

Create the file *DynamoDBUpdateItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
    "log"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials` and region from the shared configuration file `~/.aws/config` and create a new DynamoDB service client.

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Call **UpdateItem** to add the item to the table. If we encounter an error, print the error message. Otherwise, display a message that the item was updated.

```
// Update item in table Movies
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"
movieRating := "0.5"

input := &dynamodb.UpdateItemInput{
    ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
        ":r": {
            N: aws.String(movieRating),
        },
    },
    TableName: aws.String(tableName),
    Key: map[string]*dynamodb.AttributeValue{
        "Year": {
            N: aws.String(movieYear),
        },
        "Title": {
            S: aws.String(movieName),
        },
    },
    ReturnValues:     aws.String("UPDATED_NEW"),
    UpdateExpression: aws.String("set Rating = :r"),
}

_, err := svc.UpdateItem(input)
if err != nil {
    log.Fatalf("Got error calling UpdateItem: %s", err)
}

fmt.Println("Successfully updated '" + movieName + "' (" + movieYear + ") rating to " + movieRating)
```

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

# Deleting an Amazon DynamoDB Table Item
<a name="dynamo-example-delete-table-item"></a>

The following example uses the DynamoDB [DeleteItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.DeleteItem) operation to delete the item with the `year` **2015** and `title` **The Big New Movie** from the `Movies` table in your default region.

Create the file *DynamoDBUpdateItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
    "log"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials` and region from the shared configuration file `~/.aws/config` and create a new DynamoDB service client.

```
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials
// and region from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create DynamoDB client
svc := dynamodb.New(sess)
```

Call **DeleteItem** to delete the item from the table. If we encounter an error, print the error message. Otherwise, display a message that the item was deleted.

```
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"

input := &dynamodb.DeleteItemInput{
    Key: map[string]*dynamodb.AttributeValue{
        "Year": {
            N: aws.String(movieYear),
        },
        "Title": {
            S: aws.String(movieName),
        },
    },
    TableName: aws.String(tableName),
}

_, err := svc.DeleteItem(input)
if err != nil {
    log.Fatalf("Got error calling DeleteItem: %s", err)
}

fmt.Println("Deleted '" + movieName + "' (" + movieYear + ") from table " + tableName)
```

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

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

Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides resizable computing capacity—literally servers in Amazon’s data centers—that you use to build and host your software systems. The AWS SDK for Go examples can integrate Amazon EC2 into your Go applications. The examples assume you have already set up and configured the SDK (that is, you have 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/s3) repository on GitHub.

**Topics**
+ [Creating Amazon EC2 Instances with Tags or without Block Devices](ec2-example-create-images.md)
+ [Managing Amazon EC2 Instances](ec2-example-manage-instances.md)
+ [Working with Amazon EC2 Key Pairs](ec2-example-working-with-key-pairs.md)
+ [Using Regions and Availability Zones with Amazon EC2](ec2-example-regions-availability-zones.md)
+ [Working with Security Groups in Amazon EC2](ec2-example-security-groups.md)
+ [Using Elastic IP Addresses in Amazon EC2](ec2-example-elastic-ip-addresses.md)

# Creating Amazon EC2 Instances with Tags or without Block Devices
<a name="ec2-example-create-images"></a>

This Go example shows you how to:
+ Create an Amazon EC2 instance with tags or set up an instance without a block device

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/ec2) repository on GitHub.

## Scenarios
<a name="ec2-tags-scenario"></a>

In these examples, you use a series of Go routines to create Amazon EC2 instances with tags or set up an instance without a block device.

The routines use the AWS SDK for Go to perform these tasks by using these methods of the [EC2](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2) type:
+  [BlockDeviceMapping](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#BlockDeviceMapping) 
+  [RunInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.RunInstances) 
+  [CreateTags](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.CreateTags) 

## Prerequisites
<a name="ec2-tags-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.

## Create an Instance with Tags
<a name="create-an-instance-with-tags"></a>

The Amazon EC2 service has an operation for creating instances ([RunInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.RunInstances)) and another for attaching tags to instances ([CreateTags](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.CreateTags)). To create an instance with tags, call both of these operations in succession. The following example creates an instance and then adds a `Name` tag to it. The Amazon EC2 console displays the value of the `Name` tag in its list of instances.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ec2"

    "fmt"
    "log"
)

func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create EC2 service client
    svc := ec2.New(sess)

    // Specify the details of the instance that you want to create.
    runResult, err := svc.RunInstances(&ec2.RunInstancesInput{
        // An Amazon Linux AMI ID for t2.micro instances in the us-west-2 region
        ImageId:      aws.String("ami-e7527ed7"),
        InstanceType: aws.String("t2.micro"),
        MinCount:     aws.Int64(1),
        MaxCount:     aws.Int64(1),
    })

    if err != nil {
        fmt.Println("Could not create instance", err)
        return
    }

    fmt.Println("Created instance", *runResult.Instances[0].InstanceId)

    // Add tags to the created instance
    _, errtag := svc.CreateTags(&ec2.CreateTagsInput{
        Resources: []*string{runResult.Instances[0].InstanceId},
        Tags: []*ec2.Tag{
            {
                Key:   aws.String("Name"),
                Value: aws.String("MyFirstInstance"),
            },
        },
    })
    if errtag != nil {
        log.Println("Could not create tags for instance", runResult.Instances[0].InstanceId, errtag)
        return
    }

    fmt.Println("Successfully tagged instance")
}
```

You can add up to 10 tags to an instance in a single `CreateTags` operation.

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

## Create an Image without a Block Device
<a name="create-image-without-block-device"></a>

Sometimes when you create an Amazon EC2 image, you might want to explicitly exclude certain block devices. To do this, you can use the `NoDevice` parameter in [BlockDeviceMapping](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#BlockDeviceMapping). When this parameter is set to an empty string `""`, the named device isn’t mapped.

The `NoDevice` parameter is compatible only with `DeviceName`, not with any other field in `BlockDeviceMapping`. The request will fail if other parameters are present.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ec2"

    "fmt"
)

func main() {
    // Load session from shared config
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create EC2 service client
    svc := ec2.New(sess)

    opts := &ec2.CreateImageInput{
        Description: aws.String("image description"),
        InstanceId:  aws.String("i-abcdef12"),
        Name:        aws.String("image name"),
        BlockDeviceMappings: []*ec2.BlockDeviceMapping{
            {
                DeviceName: aws.String("/dev/sda1"),
                NoDevice:    aws.String(""),
            },
            {
                DeviceName: aws.String("/dev/sdb"),
                NoDevice:    aws.String(""),
            },
            {
                DeviceName: aws.String("/dev/sdc"),
                NoDevice:    aws.String(""),
            },
        },
    }
    resp, err := svc.CreateImage(opts)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println("ID: ", resp.ImageId)
}
```

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

# Managing Amazon EC2 Instances
<a name="ec2-example-manage-instances"></a>

These Go examples show you how to:
+ Describe Amazon EC2 instances
+ Manage Amazon EC2 instance monitoring
+ Start and stop Amazon EC2 instances
+ Reboot Amazon EC2 instances

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/ec2) repository on GitHub.

## Scenario
<a name="ec2-manage-instances-scenario"></a>

In these examples, you use a series of Go routines to perform several basic instance management operations.

The routines use the AWS SDK for Go to perform the operations by using these methods of the Amazon EC2 client class:
+  [DescribeInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeInstances) 
+  [MonitorInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.MonitorInstances) 
+  [UnmonitorInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.UnmonitorInstances) 
+  [StartInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.StartInstances) 
+  [StopInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.StopInstances) 
+  [RebootInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.RebootInstances) 

## Prerequisites
<a name="ec2-manage-instances-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with the lifecycle of Amazon EC2 instances. To learn more, see [Instance Lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) in the Amazon EC2 User Guide.

## Describe Your Instances
<a name="describing-your-instances"></a>

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

The Amazon EC2 service has an operation for describing instances, [DescribeInstances](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeInstances).

Import the required AWS SDK for Go packages.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ec2"

    "fmt"
)
```

Use the following code to create a session and Amazon EC2 client.

```
// Load session from shared config
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

// Create new EC2 client
ec2Svc := ec2.New(sess)
```

Call `DescribeInstances` to get detailed information for each instance.

```
// Call to get detailed information on each instance
result, err := ec2Svc.DescribeInstances(nil)
if err != nil {
    fmt.Println("Error", err)
} else {
    fmt.Println("Success", result)
}
```

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

## Manage Instance Monitoring
<a name="ec2-manage-instance-monitoring"></a>

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

Import the required AWS SDK for Go packages.

```
package main

import (
    "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/ec2"
)
```

To access Amazon EC2, create an EC2 client.

```
func main() {
    // Load session from shared config
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create new EC2 client
    svc := ec2.New(sess)
```

Based on the value of a command-line argument (ON or OFF), call either the `MonitorInstances` method of the Amazon EC2 service object to begin detailed monitoring of the specified instances, or the `UnmonitorInstances` method. Before you try to change the monitoring of these instances, use the `DryRun` parameter to test whether you have permission to change instance monitoring.

```
    if os.Args[1] == "ON" {
        input := &ec2.MonitorInstancesInput{
            InstanceIds: []*string{
                aws.String(os.Args[2]),
            },
            DryRun: aws.Bool(true),
        }
        result, err := svc.MonitorInstances(input)
        awsErr, ok := err.(awserr.Error)

        if ok && awsErr.Code() == "DryRunOperation" {
            input.DryRun = aws.Bool(false)
            result, err = svc.MonitorInstances(input)
            if err != nil {
                fmt.Println("Error", err)
            } else {
                fmt.Println("Success", result.InstanceMonitorings)
            }
        } else {
            fmt.Println("Error", err)
        }
    } else if os.Args[1] == "OFF" { // Turn monitoring off
        input := &ec2.UnmonitorInstancesInput{
            InstanceIds: []*string{
                aws.String(os.Args[2]),
            },
            DryRun: aws.Bool(true),
        }
        result, err := svc.UnmonitorInstances(input)
        awsErr, ok := err.(awserr.Error)
        if ok && awsErr.Code() == "DryRunOperation" {
            input.DryRun = aws.Bool(false)
            result, err = svc.UnmonitorInstances(input)
            if err != nil {
                fmt.Println("Error", err)
            } else {
                fmt.Println("Success", result.InstanceMonitorings)
            }
        } else {
            fmt.Println("Error", err)
        }
    }

}
```

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

## Start and Stop Instances
<a name="scenario-starting-stopping"></a>

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

Import the required AWS SDK for Go packages.

```
package main

import (
    "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/ec2"
)
```

To access Amazon EC2, create an EC2 client. The user will pass in a state value of START or STOP and the instance ID.

```
func main() {
    // Load session from shared config
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create new EC2 client
    svc := ec2.New(sess)
```

Based on the value of a command-line argument (START or STOP), call either the `StartInstances` method of the Amazon EC2 service object to start the specified instances, or the `StopInstances` method to stop them. Before you try to start or stop the selected instances, use the `DryRun` parameter to test whether you have permission to start or stop them.

```
    if os.Args[1] == "START" {
        input := &ec2.StartInstancesInput{
            InstanceIds: []*string{
                aws.String(os.Args[2]),
            },
            DryRun: aws.Bool(true),
        }
        result, err := svc.StartInstances(input)
        awsErr, ok := err.(awserr.Error)

        if ok && awsErr.Code() == "DryRunOperation" {
            // Let's now set dry run to be false. This will allow us to start the instances
            input.DryRun = aws.Bool(false)
            result, err = svc.StartInstances(input)
            if err != nil {
                fmt.Println("Error", err)
            } else {
                fmt.Println("Success", result.StartingInstances)
            }
        } else { // This could be due to a lack of permissions
            fmt.Println("Error", err)
        }
    } else if os.Args[1] == "STOP" { // Turn instances off
        input := &ec2.StopInstancesInput{
            InstanceIds: []*string{
                aws.String(os.Args[2]),
            },
            DryRun: aws.Bool(true),
        }
        result, err := svc.StopInstances(input)
        awsErr, ok := err.(awserr.Error)
        if ok && awsErr.Code() == "DryRunOperation" {
            input.DryRun = aws.Bool(false)
            result, err = svc.StopInstances(input)
            if err != nil {
                fmt.Println("Error", err)
            } else {
                fmt.Println("Success", result.StoppingInstances)
            }
        } else {
            fmt.Println("Error", err)
        }
    }
}
```

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

## Reboot Instances
<a name="ec2-reboot-instances"></a>

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

Import the required AWS SDK for Go packages.

```
package main

import (
    "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/ec2"
)
```

To access Amazon EC2, create an EC2 client. The user will pass in a state value of START or STOP and the instance ID.

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

    // Create new EC2 client
    svc := ec2.New(sess)
```

Based on the value of a command-line argument (START or STOP), call either the `StartInstances` method of the Amazon EC2 service object to start the specified instances, or the `StopInstances` method to stop them. Before you try to reboot the selected instances, use the `DryRun` parameter to test whether the instance exists and that you have permission to reboot it.

```
    input := &ec2.RebootInstancesInput{
        InstanceIds: []*string{
            aws.String(os.Args[1]),
        },
        DryRun: aws.Bool(true),
    }
    result, err := svc.RebootInstances(input)
    awsErr, ok := err.(awserr.Error)
```

If the error code is `DryRunOperation`, it means that you do have the permissions you need to reboot the instance.

```
    if ok && awsErr.Code() == "DryRunOperation" {
        input.DryRun = aws.Bool(false)
        result, err = svc.RebootInstances(input)
        if err != nil {
            fmt.Println("Error", err)
        } else {
            fmt.Println("Success", result)
        }
    } else { // This could be due to a lack of permissions
        fmt.Println("Error", err)
    }
}
```

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

# Working with Amazon EC2 Key Pairs
<a name="ec2-example-working-with-key-pairs"></a>

These Go examples show you how to:
+ Describe an Amazon EC2 key pair
+ Create an Amazon EC2 key pair
+ Delete an Amazon EC2 key pair

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/ec2) repository on GitHub.

## Scenario
<a name="ec2-key-pairs-scenario"></a>

Amazon EC2 uses public–key cryptography to encrypt and decrypt login information. Public–key cryptography uses a public key to encrypt data, then the recipient uses the private key to decrypt the data. The public and private keys are known as a key pair.

The routines use the AWS SDK for Go to perform these tasks by using these methods of the [EC2](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2) type:
+  [CreateKeyPair](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.CreateKeyPair) 
+  [DeleteKeyPair](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DeleteKeyPair) 
+  [DescribeKeyPairs](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeKeyPairs) 

## Prerequisites
<a name="ec2-key-pairs-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the SDK.
+ You are familiar with Amazon EC2 key pairs. To learn more, see [Amazon EC2 Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the Amazon EC2 User Guide.

## Describe Your Key Pairs
<a name="example-describing-your-key-pairs"></a>

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

Import the required AWS SDK for Go packages.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ec2"

    "fmt"
    "os"
)
```

Use the following code to create a session and Amazon EC2 client.

```
//    go run ec2_describe_keypairs.go
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create an EC2 service client.
```

Call `DescribeKeyPairs` to get a list of key pairs and print them out.

```
    //  Returns a list of key pairs
    result, err := svc.DescribeKeyPairs(nil)
    if err != nil {
        exitErrorf("Unable to get key pairs, %v", err)
    }

    fmt.Println("Key Pairs:")
    for _, pair := range result.KeyPairs {
        fmt.Printf("%s: %s\n", *pair.KeyName, *pair.KeyFingerprint)
    }
```

The routine uses the following utility function.

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

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

## Create a Key Pair
<a name="example-create-key-pair"></a>

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

Import the required AWS SDK for Go packages.

```
package main

import (
    "fmt"
    "os"
    "path/filepath"

    "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/ec2"
)
```

Get the key pair name passed in to the code and, to access Amazon EC2, create an EC2 client.

```
func main() {
    if len(os.Args) != 2 {
        exitErrorf("pair name required\nUsage: %s key_pair_name",
            filepath.Base(os.Args[0]))
    }
    pairName := os.Args[1]
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create an EC2 service client.
    svc := ec2.New(sess)
```

Create a new key pair with the provided name.

```
    result, err := svc.CreateKeyPair(&ec2.CreateKeyPairInput{
        KeyName: aws.String(pairName),
    })
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" {
            exitErrorf("Keypair %q already exists.", pairName)
        }
        exitErrorf("Unable to create key pair: %s, %v.", pairName, err)
    }

    fmt.Printf("Created key pair %q %s\n%s\n",
        *result.KeyName, *result.KeyFingerprint,
        *result.KeyMaterial)
}
```

The routine uses the following utility function.

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

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

## Delete a Key Pair
<a name="example-delete-key-pair"></a>

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

Import the required AWS SDK for Go packages.

```
package main

import (
    "fmt"
    "os"
    "path/filepath"

    "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/ec2"
)
```

Get the key pair name passed in to the code and, to access Amazon EC2, create an EC2 client.

```
func main() {
    if len(os.Args) != 2 {
        exitErrorf("pair name required\nUsage: %s key_pair_name",
            filepath.Base(os.Args[0]))
    }
    pairName := os.Args[1]

    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create an EC2 service client.
    svc := ec2.New(sess)
```

Delete the key pair with the provided name.

```
    _, err = svc.DeleteKeyPair(&ec2.DeleteKeyPairInput{
        KeyName: aws.String(pairName),
    })
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" {
            exitErrorf("Key pair %q does not exist.", pairName)
        }
        exitErrorf("Unable to delete key pair: %s, %v.", pairName, err)
    }

    fmt.Printf("Successfully deleted %q key pair\n", pairName)
}
```

The routine uses the following utility function.

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

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

# Using Regions and Availability Zones with Amazon EC2
<a name="ec2-example-regions-availability-zones"></a>

These Go examples show you how to retrieve details about AWS Regions and Availability Zones.

The code in this example uses the AWS SDK for Go to perform these tasks by using these methods of the Amazon EC2 client class:
+  [DescribeRegions](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeRegions) 
+  [DescribeAvailabilityZones](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeAvailabilityZones) 

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/ec2) repository on GitHub.

## Scenario
<a name="ec2-scenario-regions-and-azs"></a>

Amazon EC2 is hosted in multiple locations worldwide. These locations are composed of AWS Regions and Availability Zones. Each region is a separate geographic area with multiple, isolated locations known as Availability Zones. Amazon EC2 provides the ability to place instances and data in these multiple locations.

In this example, you use Go code to retrieve details about regions and Availability Zones. The code uses the AWS SDK for Go tomanage instances by using the following methods of the Amazon EC2 client class:
+  [DescribeAvailabilityZones](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeAvailabilityZones) 
+  [DescribeRegions](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeRegions) 

## Prerequisites
<a name="ec2-regions-and-azs-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with AWS Regions and Availability Zones. To learn more, see [Regions and Availability Zones](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) in the Amazon EC2 User Guide or [Regions and Availability Zones](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/resources.html) in the Amazon EC2 User Guide.

## List the Regions
<a name="list-the-regions"></a>

This example lists the regions in which Amazon EC2 is available.

To get started, create a new Go file named `regions_and_availability.go`.

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

```
package main

import (
    "fmt"

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

In the `main` function, create a session with credentials from the shared credentials file, `~/.aws/credentials`, and create a new EC2 client.

```
func main() {
    // Load session from shared config
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create new EC2 client
    svc := ec2.New(sess)
```

Print out the list of regions that work with Amazon EC2 that are returned by calling `DescribeRegions`.

```
    resultRegions, err := svc.DescribeRegions(nil)
    if err != nil {
        fmt.Println("Error", err)
        return
    }
```

Add a call that retrieves Availability Zones only for the region of the EC2 service object.

```
    resultAvalZones, err := svc.DescribeAvailabilityZones(nil)
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", resultAvalZones.AvailabilityZones)
}
```

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

# Working with Security Groups in Amazon EC2
<a name="ec2-example-security-groups"></a>

These Go examples show you how to:
+ Retrieve information about your security groups
+ Create a security group to access an Amazon EC2 instance
+ Delete an existing security group

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/ec2) repository on GitHub.

## Scenario
<a name="scenario-security-groups"></a>

An Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or more instances. You add rules to each security group to allow traffic to or from its associated instances. You can modify the rules for a security group at any time; the new rules are automatically applied to all instances that are associated with the security group.

The code in this example uses the AWS SDK for Go to perform these tasks by using these methods of the Amazon EC2 client class:
+  [DescribeSecurityGroups](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeSecurityGroups) 
+  [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.AuthorizeSecurityGroupIngress) 
+  [CreateSecurityGroup](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.CreateSecurityGroup) 
+  [DescribeVpcs](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeVpcs) 
+  [DeleteSecurityGroup](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DeleteSecurityGroup) 

## Prerequisites
<a name="scenario-security-groups-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with Amazon EC2 security groups. To learn more, see [Amazon EC2 Amazon Security Groups for Linux Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) in the Amazon EC2 User Guide or [Amazon EC2 Amazon Security Groups for Windows Instances](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/using-network-security.html) in the Amazon EC2 User Guide.

## Describing Your Security Groups
<a name="ec2-describe-security-groups"></a>

This example describes the security groups by IDs that are passed into the routine. It takes a space separated list of group IDs as input.

To get started, create a new Go file named `ec2_describe_security_groups.go`.

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

```
import (
    "fmt"
    "os"
    "path/filepath"

    "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/ec2"
)
```

In the `main` function, get the security group ID that is passed in.

```
if len(os.Args) < 2 {
    exitErrorf("Security Group ID required\nUsage: %s group_id ...",
        filepath.Base(os.Args[0]))
}
groupIds := os.Args[1:]
```

Initialize a session and create an EC2 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create an EC2 service client.
svc := ec2.New(sess)
```

Obtain and print out the security group descriptions. You will explicitly check for errors caused by an invalid group ID.

```
result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
    GroupIds: aws.StringSlice(groupIds),
})
if err != nil {
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case "InvalidGroupId.Malformed":
            fallthrough
        case "InvalidGroup.NotFound":
            exitErrorf("%s.", aerr.Message())
        }
    }
    exitErrorf("Unable to get descriptions for security groups, %v", err)
}

fmt.Println("Security Group:")
for _, group := range result.SecurityGroups {
    fmt.Println(group)
}
```

The following utility function is used by this example to display errors.

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

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

## Creating a Security Group
<a name="create-security-group"></a>

You can create new Amazon EC2 security groups. To do this, you use the [CreateSecurityGroup](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.CreateSecurityGroup) method.

This example creates a new security group with the given name and description for access to open ports 80 and 22. If a VPC ID is not provided, it associates the security group with the first VPC in the account.

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

```
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/ec2"
)
```

Get the parameters (name, description, and optional ID of the VPC) that are passed in to the routine.

```
namePtr := flag.String("n", "", "Group Name")
descPtr := flag.String("d", "", "Group Description")
vpcIDPtr := flag.String("vpc", "", "(Optional) VPC ID to associate security group with")

flag.Parse()

if *namePtr == "" || *descPtr == "" {
    flag.PrintDefaults()
    exitErrorf("Group name and description require")
}
```

Create a session and Amazon EC2 client.

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

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

Create an Amazon EC2 client. If the VPC ID was not provided, retrieve the first one in the account.

```
if *vpcIDPtr == "" {
    // Get a list of VPCs so we can associate the group with the first VPC.
    result, err := svc.DescribeVpcs(nil)
    if err != nil {
        exitErrorf("Unable to describe VPCs, %v", err)
    }
    if len(result.Vpcs) == 0 {
        exitErrorf("No VPCs found to associate security group with.")
    }

    *vpcIDPtr = aws.StringValue(result.Vpcs[0].VpcId)
}
```

Create the security group with the VPC ID, name, and description.

```
createRes, err := svc.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{
    GroupName:   aws.String(*namePtr),
    Description: aws.String(*descPtr),
    VpcId:       aws.String(*vpcIDPtr),
})
if err != nil {
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case "InvalidVpcID.NotFound":
            exitErrorf("Unable to find VPC with ID %q.", *vpcIDPtr)
        case "InvalidGroup.Duplicate":
            exitErrorf("Security group %q already exists.", *namePtr)
        }
    }
    exitErrorf("Unable to create security group %q, %v", *namePtr, err)
}

fmt.Printf("Created security group %s with VPC %s.\n",
    aws.StringValue(createRes.GroupId), *vpcIDPtr)
```

Add permissions to the security group.

```
_, err = svc.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{
    GroupName: aws.String(*namePtr),
    IpPermissions: []*ec2.IpPermission{
        // Can use setters to simplify seting multiple values without the
        // needing to use aws.String or associated helper utilities.
        (&ec2.IpPermission{}).
            SetIpProtocol("tcp").
            SetFromPort(80).
            SetToPort(80).
            SetIpRanges([]*ec2.IpRange{
                {CidrIp: aws.String("0.0.0.0/0")},
            }),
        (&ec2.IpPermission{}).
            SetIpProtocol("tcp").
            SetFromPort(22).
            SetToPort(22).
            SetIpRanges([]*ec2.IpRange{
                (&ec2.IpRange{}).
                    SetCidrIp("0.0.0.0/0"),
            }),
    },
})
if err != nil {
    exitErrorf("Unable to set security group %q ingress, %v", *namePtr, err)
}

fmt.Println("Successfully set security group ingress")
```

The following utility function is used by this example.

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

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

## Deleting a Security Group
<a name="delete-security-group"></a>

You can delete an Amazon EC2 security group in code. To do this, you use the [DeleteSecurityGroup](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DeleteSecurityGroup) method.

This example deletes a security group with the given group ID.

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

```
import (
    "fmt"
    "os"
    "path/filepath"

    "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/ec2"
)
```

Get the group ID that is passed in to the routine.

```
if len(os.Args) != 2 {
    exitErrorf("Security Group ID required\nUsage: %s group_id",
        filepath.Base(os.Args[0]))
}
groupID := os.Args[1]
```

Create a session.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create an EC2 service client.
svc := ec2.New(sess)
```

Then delete the security group with the group ID that is passed in.

```
_, err = svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{
    GroupId: aws.String(groupID),
})
if err != nil {
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case "InvalidGroupId.Malformed":
            fallthrough
        case "InvalidGroup.NotFound":
            exitErrorf("%s.", aerr.Message())
        }
    }
    exitErrorf("Unable to get descriptions for security groups, %v.", err)
}

fmt.Printf("Successfully delete security group %q.\n", groupID)
```

This example uses the following utility function.

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

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

# Using Elastic IP Addresses in Amazon EC2
<a name="ec2-example-elastic-ip-addresses"></a>

These Go examples show you how to:
+ Describe Amazon EC2 instance IP addresses
+ Allocate addresses to Amazon EC2 instances
+ Release Amazon EC2 instance IP addresses

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/ec2) repository on GitHub.

## Scenario
<a name="ec-allocate-address-scenario"></a>

An Elastic IP address is a static IP address designed for dynamic cloud computing that is associated with your AWS account. It is a public IP address, reachable from the Internet. If your instance doesn’t have a public IP address, you can associate an Elastic IP address with the instance to enable communication with the Internet.

In this example, you use a series of Go routines to perform several Amazon EC2 operations involving Elastic IP addresses. The routines use the AWS SDK for Go to manage Elastic IP addresses by using these methods of the Amazon EC2 client class:
+  [DescribeAddresses](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.DescribeAddresses) 
+  [AllocateAddress](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.AllocateAddress) 
+  [AssociateAddress](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.AssociateAddress) 
+  [ReleaseAddress](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.ReleaseAddress) 

## Prerequisites
<a name="ec-allocate-address-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with Elastic IP addresses in Amazon EC2. To learn more, see [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) in the Amazon EC2 User Guide or [Elastic IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-ip-addresses-eip.html) in the Amazon EC2 User Guide.

## Describe Instance IP Addresses
<a name="ec2-example-describe"></a>

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

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

```
package main

import (
    "fmt"
    "os"

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

### Get the Address Descriptions
<a name="get-the-address-descriptions"></a>

This routine prints out the Elastic IP Addresses for the account’s VPC. Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials`, and create a new EC2 service client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create an EC2 service client.
    svc := ec2.New(sess)
```

Make the API request to EC2 filtering for the addresses in the account’s VPC.

```
    result, err := svc.DescribeAddresses(&ec2.DescribeAddressesInput{
        Filters: []*ec2.Filter{
            {
                Name:   aws.String("domain"),
                Values: aws.StringSlice([]string{"vpc"}),
            },
        },
    })
    if err != nil {
        exitErrorf("Unable to elastic IP address, %v", err)
    }

    // Printout the IP addresses if there are any.
    if len(result.Addresses) == 0 {
        fmt.Printf("No elastic IPs for %s region\n", *svc.Config.Region)
    } else {
        fmt.Println("Elastic IPs")
        for _, addr := range result.Addresses {
            fmt.Println("*", fmtAddress(addr))
        }
    }
}
```

The `fmtAddress` and `exitErrorf` functions are utility functions used in the example.

```
func fmtAddress(addr *ec2.Address) string {
    out := fmt.Sprintf("IP: %s,  allocation id: %s",
        aws.StringValue(addr.PublicIp), aws.StringValue(addr.AllocationId))
    if addr.InstanceId != nil {
        out += fmt.Sprintf(", instance-id: %s", *addr.InstanceId)
    }
    return out
}

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

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

## Allocate Addresses to Instances
<a name="ec2-example-allocate"></a>

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

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

```
package main

import (
    "fmt"
    "os"
    "path/filepath"

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

This routine attempts to allocate a VPC Elastic IP address for the current region. The IP address requires and will be associated with the instance ID that is passed in.

```
func main() {
    if len(os.Args) != 2 {
        exitErrorf("instance ID required\nUsage: %s instance_id",
            filepath.Base(os.Args[0]))
    }
    instanceID := os.Args[1]
```

You will need to initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials`, and create a new Amazon EC2 service client.

```
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create an EC2 service client.
    svc := ec2.New(sess)
```

Call [AllocateAddress](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.AllocateAddress), passing in “vpc” as the Domain value.

```
    allocRes, err := svc.AllocateAddress(&ec2.AllocateAddressInput{
        Domain: aws.String("vpc"),
    })
    if err != nil {
        exitErrorf("Unable to allocate IP address, %v", err)
    }
```

Call [AssociateAddress](https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.AssociateAddress) to associate the new Elastic IP address with an existing Amazon EC2 instance, and print out the results.

```
    assocRes, err := svc.AssociateAddress(&ec2.AssociateAddressInput{
        AllocationId: allocRes.AllocationId,
        InstanceId:   aws.String(instanceID),
    })
    if err != nil {
        exitErrorf("Unable to associate IP address with %s, %v",
            instanceID, err)
    }

    fmt.Printf("Successfully allocated %s with instance %s.\n\tallocation id: %s, association id: %s\n",
        *allocRes.PublicIp, instanceID, *allocRes.AllocationId, *assocRes.AssociationId)
}
```

This example also uses the `exitErrorf` utility function.

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

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

## Release Instance IP Addresses
<a name="ec2-example-release-instance-addresses"></a>

This routine releases an Elastic IP address allocation ID. If the address is associated with an Amazon EC2 instance, the association is removed.

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

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

```
package main

import (
    "fmt"
    "os"
    "path/filepath"

    "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/ec2"
)
```

The routine requires that the user pass in the allocation ID of the Elastic IP address.

```
func main() {
    if len(os.Args) != 2 {
        exitErrorf("allocation ID required\nUsage: %s allocation_id",
            filepath.Base(os.Args[0]))
    }
    allocationID := os.Args[1]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials`, and create a new EC2 service client.

```
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create an EC2 service client.
    svc := ec2.New(sess)
```

Attempt to release the Elastic IP address by using the allocation ID.

```
    _, err = svc.ReleaseAddress(&ec2.ReleaseAddressInput{
        AllocationId: aws.String(allocationID),
    })
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidAllocationID.NotFound" {
            exitErrorf("Allocation ID %s does not exist", allocationID)
        }
        exitErrorf("Unable to release IP address for allocation %s, %v",
            allocationID, err)
    }

    fmt.Printf("Successfully released allocation ID %s\n", allocationID)
}
```

This example uses the `fmtAddress` and `exitErrorf` utility functions.

```
func fmtAddress(addr *ec2.Address) string {
    out := fmt.Sprintf("IP: %s,  allocation id: %s",
        aws.StringValue(addr.PublicIp), aws.StringValue(addr.AllocationId))
    if addr.InstanceId != nil {
        out += fmt.Sprintf(", instance-id: %s", *addr.InstanceId)
    }
    return out
}

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

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

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

Amazon Glacier is a secure, durable, and extremely low-cost cloud storage service for data archiving and long-term backup. The AWS SDK for Go examples can integrate Amazon Glacier 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/glacier) repository on GitHub.

## The Scenario
<a name="the-scenario"></a>

Amazon Glacier is a secure cloud storage service for data archiving and long-term backup. The service is optimized for infrequently accessed data where a retrieval time of several hours is suitable. These examples show you how to create a vault and upload an archive with Go. The methods used include:
+  [CreateVault](https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/#Glacier.CreateVault) 
+  [UploadArchive](https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/#Glacier.UploadArchive) 

## Prerequisites
<a name="create-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with the Amazon Glacier data model. To learn more, see [Amazon Glacier Data Model](https://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-data-model.html) in the Amazon Glacier Developer Guide.

## Create a Vault
<a name="create-a-vault"></a>

The following example uses the Amazon Glacier[CreateVault](https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/#Glacier.CreateVault) operation to create a vault named `YOUR_VAULT_NAME`.

```
import (
    "log"

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

func main() {
    // Initialize a session that the SDK uses to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and configuration from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create Glacier client in default region
    svc := glacier.New(sess)

    // start snippet
    _, err := svc.CreateVault(&glacier.CreateVaultInput{
        VaultName: aws.String("YOUR_VAULT_NAME"),
    })
    if err != nil {
        log.Println(err)
        return
    }

    log.Println("Created vault!")
    // end snippet
}
```

## Upload an Archive
<a name="upload-an-archive"></a>

The following example assumes you have a vault named `YOUR_VAULT_NAME`. It uses the Amazon Glacier[UploadArchive](https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/#Glacier.UploadArchive) operation to upload a single reader object as an entire archive. The AWS SDK for Go automatically computes the tree hash checksum for the data to be uploaded.

```
import (
    "bytes"
    "log"

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

func main() {
    // Initialize a session that the SDK uses to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and configuration from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create Glacier client in default region
    svc := glacier.New(sess)

    // start snippet
    vaultName := "YOUR_VAULT_NAME"

    result, err := svc.UploadArchive(&glacier.UploadArchiveInput{
        VaultName: &vaultName,
        Body:      bytes.NewReader(make([]byte, 2*1024*1024)), // 2 MB buffer
    })
    if err != nil {
        log.Println("Error uploading archive.", err)
        return
    }

    log.Println("Uploaded to archive", *result.ArchiveId)
    // end snippet
}
```

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

AWS Identity and Access Management (IAM) is a web service that enables AWS customers to manage users and user permissions in AWS. The service is targeted at organizations with multiple users or systems in the cloud that use AWS products. With IAM, you can centrally manage users, security credentials such as access keys, and permissions that control which AWS resources users can access.

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/s3) repository on GitHub.

**Topics**
+ [Managing IAM Users](iam-example-managing-users.md)
+ [Managing IAM Access Keys](iam-example-managing-access-keys.md)
+ [Managing IAM Account Aliases](iam-example-account-aliases.md)
+ [Working with IAM Policies](iam-example-policies.md)
+ [Working with IAM Server Certificates](iam-example-server-certificates.md)

# Managing IAM Users
<a name="iam-example-managing-users"></a>

This Go example shows you how to create, update, view, and delete IAM users. 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/iam) repository on GitHub.

## Scenario
<a name="iam-users-scenario"></a>

In this example, you use a series of Go routines to manage users in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreateUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreateUser) 
+  [ListUsers](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListUsers) 
+  [UpdateUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.UpdateUser) 
+  [GetUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetUser) 
+  [DeleteUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteUser) 
+  [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetAccountAuthorizationDetails) 

## Prerequisites
<a name="iam-users-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM users. To learn more, see [IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) in the IAM User Guide.

## Create a New IAM User
<a name="iam-example-create-user"></a>

This code creates a new IAM user.

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

```
import (
    "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/iam"
)
```

The code takes the new user name as an argument, and then calls `GetUser` with the user name.

```
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create a IAM service client.
svc := iam.New(sess)

_, err = svc.GetUser(&iam.GetUserInput{
    UserName: &os.Args[1],
})
```

If you receive a `NoSuchEntity` error, call `CreateUser` because the user doesn’t exist.

```
if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException {
    result, err := svc.CreateUser(&iam.CreateUserInput{
        UserName: &os.Args[1],
    })

    if err != nil {
        fmt.Println("CreateUser Error", err)
        return
    }

    fmt.Println("Success", result)
} else {
    fmt.Println("GetUser Error", err)
}
```

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

## List IAM Users in Your Account
<a name="iam-example-list-user"></a>

You can get a list of the users in your account and print the list to the console.

Create a new Go file named `iam_listusers.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"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create a IAM service client.
svc := iam.New(sess)
```

Call `ListUsers` and print the results.

```
result, err := svc.ListUsers(&iam.ListUsersInput{
    MaxItems: aws.Int64(10),
})

if err != nil {
    fmt.Println("Error", err)
    return
}

for i, user := range result.Users {
    if user == nil {
        continue
    }
    fmt.Printf("%d user %s created %v\n", i, *user.UserName, user.CreateDate)
}
```

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

## Update a User’s Name
<a name="iam-example-update-user"></a>

In this example, you change the name of an IAM user to a new value.

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

```
import (
    "fmt"
    "os"

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

Set up a new IAM client.

```
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create a IAM service client.
svc := iam.New(sess)
```

Call `UpdateUser`, passing in the original user name and the new name, and print the results.

```
result, err := svc.UpdateUser(&iam.UpdateUserInput{
    UserName:    &os.Args[1],
    NewUserName: &os.Args[2],
})

if err != nil {
    fmt.Println("Error", err)
    return
}

fmt.Println("Success", result)
```

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

## Delete an IAM User
<a name="iam-example-delete-user"></a>

In this example, you delete an IAM user.

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

```
import (
    "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/iam"
)
```

Set up a new IAM client.

```
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )
    svc := iam.New(sess)
```

Call `DeleteUser`, passing in the user name, and print the results. If the user doesn’t exist, display an error.

```
    _, err = svc.DeleteUser(&iam.DeleteUserInput{
        UserName: &os.Args[1],
    })

    // If the user does not exist than we will log an error.
    if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException {
        fmt.Printf("User %s does not exist\n", os.Args[1])
        return
    } else if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("User %s has been deleted\n", os.Args[1])
```

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

## List the IAM Users who have Administrator Privileges
<a name="iam-example-get-admins"></a>

In this example, you list the IAM users who have administrator privileges (a policy or attached policy of the user or a group to which the user belongs has the name **AdministratorAccess**.

Create a new Go file named `IamGetAdmins.go`. Import the following packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"

    "fmt"
    "os"
)
```

Create a method to determine whether a user has a policy that has administrator privileges.

```
func UserPolicyHasAdmin(user *iam.UserDetail, admin string) bool {
    for _, policy := range user.UserPolicyList {
        if *policy.PolicyName == admin {
            return true
        }
    }

    return false
}
```

Create a method to determine whether a user has an attached policy that has administrator privileges.

```
func AttachedUserPolicyHasAdmin(user *iam.UserDetail, admin string) bool {
    for _, policy := range user.AttachedManagedPolicies {
        if *policy.PolicyName == admin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether a group has a policy that has adminstrator privileges.

```
func GroupPolicyHasAdmin(svc *iam.IAM, group *iam.Group, admin string) bool {
    input := &iam.ListGroupPoliciesInput{
        GroupName: group.GroupName,
    }

    result, err := svc.ListGroupPolicies(input)
    if err != nil {
        fmt.Println("Got error calling ListGroupPolicies for group", group.GroupName)
    }

    // Wade through policies
    for _, policyName := range result.PolicyNames {
        if
        *policyName == admin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether a group has an attached policy that has administrator privileges.

```
func AttachedGroupPolicyHasAdmin(svc *iam.IAM, group *iam.Group, admin string) bool {
    input := &iam.ListAttachedGroupPoliciesInput{GroupName: group.GroupName}
    result, err := svc.ListAttachedGroupPolicies(input)
    if err != nil {
        fmt.Println("Got error getting attached group policies:")
        fmt.Println(err.Error())
        os.Exit(1)
    }

    for _, policy := range result.AttachedPolicies {
        if *policy.PolicyName == admin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether any group to which the user belongs has administrator privileges.

```
func UsersGroupsHaveAdmin(svc *iam.IAM, user *iam.UserDetail, admin string) bool {
    input := &iam.ListGroupsForUserInput{UserName: user.UserName}
    result, err := svc.ListGroupsForUser(input)
    if err != nil {
        fmt.Println("Got error getting groups for user:")
        fmt.Println(err.Error())
        os.Exit(1)
    }

    for _, group := range result.Groups {
        groupPolicyHasAdmin := GroupPolicyHasAdmin(svc, group, admin)

        if groupPolicyHasAdmin {
            return true
        }

        attachedGroupPolicyHasAdmin := AttachedGroupPolicyHasAdmin(svc, group, admin)

        if attachedGroupPolicyHasAdmin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether a user has administrator privileges.

```
func IsUserAdmin(svc *iam.IAM, user *iam.UserDetail, admin string) bool {
    // Check policy, attached policy, and groups (policy and attached policy)
    policyHasAdmin := UserPolicyHasAdmin(user, admin)
    if policyHasAdmin {
        return true
    }

    attachedPolicyHasAdmin := AttachedUserPolicyHasAdmin(user, admin)
    if attachedPolicyHasAdmin {
        return true
    }

    userGroupsHaveAdmin := UsersGroupsHaveAdmin(svc, user, admin)
    if userGroupsHaveAdmin {
        return true
    }

    return false
}
```

Create a main method with an IAM client in `us-west-2`. Create variables to keep track of how many users we have and how many of those have administrator privileges.

```
sess, err := session.NewSession()
if err != nil {
    fmt.Println("Got error creating new session")
    fmt.Println(err.Error())
    os.Exit(1)
}

svc := iam.New(sess, &aws.Config{Region: aws.String("us-west-2")})

numUsers := 0
numAdmins := 0
```

Create the input for and call `GetAccountAuthorizationDetails`. If there is an error, print an error message and quit.

```
user := "User"
input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}}
resp, err := svc.GetAccountAuthorizationDetails(input)
if err != nil {
    fmt.Println("Got error getting account details")
    fmt.Println(err.Error())
    os.Exit(1)
}
```

Loop through the users. If a user has adminstrator privileges, print their name and increment the number of users who have adminstrator privileges.

```
adminName := "AdministratorAccess"

// Wade through resulting users
for _, user := range resp.UserDetailList {
    numUsers += 1

    isAdmin := IsUserAdmin(svc, user, adminName)

    if isAdmin {
        fmt.Println(*user.UserName)
        numAdmins += 1
    }
}
```

If we did not get all of the users in the first call to `GetAccountAuthorizationDetails`, loop through the next set of users and determine which of those have adminstrator privileges.

```
for *resp.IsTruncated {
    input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}, Marker: resp.Marker}
    resp, err = svc.GetAccountAuthorizationDetails(input)
    if err != nil {
        fmt.Println("Got error getting account details")
        fmt.Println(err.Error())
        os.Exit(1)
    }

    // Wade through resulting users
    for _, user := range resp.UserDetailList {
        numUsers += 1

        isAdmin := IsUserAdmin(svc, user, adminName)

        if isAdmin {
            fmt.Println(*user.UserName)
            numAdmins += 1
        }
    }
}
```

Finally, display the number of users who have administrator access.

```
fmt.Println("")
fmt.Println("Found", numAdmins, "admin(s) out of", numUsers, "user(s).")
```

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

# Managing IAM Access Keys
<a name="iam-example-managing-access-keys"></a>

This Go example shows you how to create, modify, view, or rotate IAM access keys. 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/iam) repository on GitHub.

## Scenario
<a name="iam-access-keys-scenario"></a>

Users need their own access keys to make programmatic calls to the AWS SDK for Go. To fill this need, you can create, modify, view, or rotate access keys (access key IDs and secret access keys) for IAM users. By default, when you create an access key its status is Active, which means the user can use the access key for API calls.

In this example, you use a series of Go routines to manage access keys in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreateAccessKey](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreateAccessKey) 
+  [ListAccessKeys](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListAccessKeys) 
+  [GetAccessKeyLastUsed](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetAccessKeyLastUsed) 
+  [UpdateAccessKey](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.UpdateAccessKey) 
+  [DeleteAccessKey](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteAccessKey) 

## Prerequisites
<a name="iam-access-keys-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM access keys. To learn more, see [Managing Access Keys for IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) in the IAM User Guide.

## Create a New IAM Access Key
<a name="iam-example-create-access-key"></a>

This code creates a new IAM access key for the IAM user named IAM\$1USER\$1NAME.

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

```
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/iam"
)
```

Set up the session.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `CreateAccessKey` and print the results.

```
    result, err := svc.CreateAccessKey(&iam.CreateAccessKeyInput{
        UserName: aws.String("IAM_USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", *result.AccessKey)
}
```

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

## List a User’s Access Keys
<a name="iam-example-list-access-keys"></a>

In this example, you get a list of the access keys for a user and print the list to the console.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `ListAccessKeys` and print the results.

```
    result, err := svc.ListAccessKeys(&iam.ListAccessKeysInput{
        MaxItems: aws.Int64(5),
        UserName: aws.String("IAM_USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", result)
}
```

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

## Get the Last Use for an Access Key
<a name="iam-example-last-use"></a>

In this example, you find out when an access key was last used.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `GetAccessKeyLastUsed`, passing in the access key ID, and print the results.

```
    result, err := svc.GetAccessKeyLastUsed(&iam.GetAccessKeyLastUsedInput{
        AccessKeyId: aws.String("ACCESS_KEY_ID"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", *result.AccessKeyLastUsed)
}
```

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

## Update Access Key Status
<a name="iam-example-update-access-key"></a>

In this example, you delete an IAM user.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `UpdateAccessKey`, passing in the access key ID, status (making it active in this case), and user name.

```
    _, err = svc.UpdateAccessKey(&iam.UpdateAccessKeyInput{
        AccessKeyId: aws.String("ACCESS_KEY_ID"),
        Status:      aws.String(iam.StatusTypeActive),
        UserName:    aws.String("USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Access Key updated")
}
```

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

## Delete an Access Key
<a name="iam-example-delete-access-key"></a>

In this example, you delete an access key.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `DeleteAccessKey`, passing in the access key ID and user name.

```
    result, err := svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{
        AccessKeyId: aws.String("ACCESS_KEY_ID"),
        UserName:    aws.String("USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", result)
}
```

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

# Managing IAM Account Aliases
<a name="iam-example-account-aliases"></a>

This Go example shows you how to create, list, and delete IAM account aliases. 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/iam) repository on GitHub.

## Scenario
<a name="iam-aliases-scenario"></a>

You can use a series of Go routines to manage aliases in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreateAccountAlias](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreateAccountAlias) 
+  [ListAccountAliases](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListAccountAliases) 
+  [DeleteAccountAlias](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteAccountAlias) 

## Prerequisites
<a name="iam-aliases-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM account aliases. To learn more, see [Your AWS account ID and Its Alias](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html) in the IAM User Guide.

## Create a New IAM Account Alias
<a name="iam-example-create-alias"></a>

This code creates a new IAM user.

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

```
package main

import (
    "fmt"
    "os"

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

Set up a session and an IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

The code takes the new alias as an argument, and then calls `CreateAccountAlias` with the alias name.

```
    _, err = svc.CreateAccountAlias(&iam.CreateAccountAliasInput{
        AccountAlias: &os.Args[1],
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("Account alias %s has been created\n", os.Args[1])
```

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

## List IAM Account Aliases
<a name="iam-example-list-aliases"></a>

This code lists the aliases for your IAM account.

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

```
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/iam"
)
```

Set up a session and an IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

The code calls `ListAccountAliases`, specifying to return a maximum of 10 items.

```
    result, err := svc.ListAccountAliases(&iam.ListAccountAliasesInput{
        MaxItems: aws.Int64(10),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    for i, alias := range result.AccountAliases {
        if alias == nil {
            continue
        }
        fmt.Printf("Alias %d: %s\n", i, *alias)
    }
}
```

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

## Delete an IAM Account Alias
<a name="iam-example-delete-aliases"></a>

This code deletes a specified IAM account alias.

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

```
package main

import (
    "fmt"
    "os"

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

Set up a session and an IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

The code calls `ListAccountAliases`, specifying to return a maximum of 10 items.

```
    _, err = svc.DeleteAccountAlias(&iam.DeleteAccountAliasInput{
        AccountAlias: &os.Args[1],
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("Alias %s has been deleted\n", os.Args[1])
```

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

# Working with IAM Policies
<a name="iam-example-policies"></a>

This Go example shows you how to create, get, attach, and detach IAM policies. 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/iam) repository on GitHub.

## Scenario
<a name="iam-policies-scenario"></a>

You grant permissions to a user by creating a policy, which is a document that lists the actions that a user can perform and the resources those actions can affect. Any actions or resources that are not explicitly allowed are denied by default. Policies can be created and attached to users, groups of users, roles assumed by users, and resources.

In this example, you use a series of Go routines to manage policies in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreatePolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreatePolicy) 
+  [GetPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetPolicy) 
+  [ListAttachedRolePolicies](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListAttachedRolePolicies) 
+  [AttachRolePolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.AttachRolePolicy) 
+  [DetachRolePolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DetachRolePolicy) 

## Prerequisites
<a name="iam-policies-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM policies. To learn more, see [Overview of Access Management: Permissions and Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html) in the IAM User Guide.

## Create an IAM Policy
<a name="iam-example-create-policy"></a>

This code creates a new IAM Policy. Create a new Go file named `iam_createpolicy.go`.

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

```
package main

import (
    "encoding/json"
    "fmt"

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

Define two structs. The first is the definition of the policies to upload to IAM.

```
type PolicyDocument struct {
    Version   string
    Statement []StatementEntry
}
```

The second dictates what this policy will allow or disallow.

```
type StatementEntry struct {
    Effect   string
    Action   []string
    Resource string
}
```

Set up the session and IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Build the policy document using the structures defined earlier.

```
    policy := PolicyDocument{
        Version: "2012-10-17",		 	 	 
        Statement: []StatementEntry{
            StatementEntry{
                Effect: "Allow",
                Action: []string{
                    "logs:CreateLogGroup", // Allow for creating log groups
                },
                Resource: "RESOURCE ARN FOR logs:*",
            },
            StatementEntry{
                Effect: "Allow",
                // Allows for DeleteItem, GetItem, PutItem, Scan, and UpdateItem
                Action: []string{
                    "dynamodb:DeleteItem",
                    "dynamodb:GetItem",
                    "dynamodb:PutItem",
                    "dynamodb:Scan",
                    "dynamodb:UpdateItem",
                },
                Resource: "RESOURCE ARN FOR dynamodb:*",
            },
        },
    }
```

Marshal the policy to JSON and pass to `CreatePolicy`.

```
    b, err := json.Marshal(&policy)
    if err != nil {
        fmt.Println("Error marshaling policy", err)
        return
    }

    result, err := svc.CreatePolicy(&iam.CreatePolicyInput{
        PolicyDocument: aws.String(string(b)),
        PolicyName:     aws.String("myDynamodbPolicy"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("New policy", result)
}
```

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

## Get an IAM Policy
<a name="iam-example-get-policy"></a>

In this example, you retrieve an existing policy from IAM. Create a new Go file named `iam_getpolicy.go`.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `GetPolicy`, passing in the ARN for the policy (which is hard coded in this example), and print the results.

```
    arn := "arn:aws:iam::aws:policy/AWSLambdaExecute"
    result, err := svc.GetPolicy(&iam.GetPolicyInput{
        PolicyArn: &arn,
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("%s - %s\n", arn, *result.Policy.Description)
```

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

## Attach a Managed Role Policy
<a name="iam-example-attach-managed-role-policy"></a>

In this example, you attach an IAM managed role policy. Create a new Go file named `iam_attachuserpolicy.go`. You’ll call the `ListAttachedRolePolicies` method of the IAM service object, which returns an array of managed policies.

Then, you’ll check the array members to see if the policy you want to attach to the role is already attached. If the policy isn’t attached, you’ll call the `AttachRolePolicy` method to attach it.

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

```
package main

import (
    "fmt"
    "os"

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

Set up a new IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Declare variables to hold the name and ARN of the policy.

```
    var pageErr error
    policyName := "AmazonDynamoDBFullAccess"
    policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
```

Paginate through all the role policies. If your role exists on any role policy, you set the `pageErr` and return `false`, stopping the pagination.

```
    err = svc.ListAttachedRolePoliciesPages(
        &iam.ListAttachedRolePoliciesInput{
            RoleName: &os.Args[1],
        },
        func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool {
            if page != nil && len(page.AttachedPolicies) > 0 {
                for _, policy := range page.AttachedPolicies {
                    if *policy.PolicyName == policyName {
                        pageErr = fmt.Errorf("%s is already attached to this role", policyName)
                        return false
                    }
                }
                // We should keep paginating because we did not find our role
                return true
            }
            return false
        },
    )
```

If your role policy is not attached already, call `AttachRolePolicy`.

```
    if pageErr != nil {
        fmt.Println("Error", pageErr)
        return
    }

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{
        PolicyArn: &policyArn,
        RoleName:  &os.Args[1],
    })

    if err != nil {
        fmt.Println("Unable to attach role policy to role")
        return
    }
    fmt.Println("Role attached successfully")
```

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

## Detach a Managed Role Policy
<a name="iam-example-detach-managed-role-policy"></a>

In this example, you detach a role policy. Once again, you call the `ListAttachedRolePolicies` method of the IAM service object, which returns an array of managed policies.

Then, check the array members to see if the policy you want to detach from the role is attached. If the policy is attached, call the `DetachRolePolicy` method to detach it.

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

```
package main

import (
    "fmt"
    "os"

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

Set up a new IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Declare variables to hold the name and ARN of the policy.

```
    foundPolicy := false
    policyName := "AmazonDynamoDBFullAccess"
    policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
```

Paginate through all the role policies. If the role exists on any role policy, you stop iterating and detach the role.

```
    err = svc.ListAttachedRolePoliciesPages(
        &iam.ListAttachedRolePoliciesInput{
            RoleName: &os.Args[1],
        },
        func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool {
            if page != nil && len(page.AttachedPolicies) > 0 {
                for _, policy := range page.AttachedPolicies {
                    if *policy.PolicyName == policyName {
                        foundPolicy = true
                        return false
                    }
                }
                return true
            }
            return false
        },
    )

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    if !foundPolicy {
        fmt.Println("Policy was not attached to role")
        return
    }

    _, err = svc.DetachRolePolicy(&iam.DetachRolePolicyInput{
        PolicyArn: &policyArn,
        RoleName:  &os.Args[1],
    })

    if err != nil {
        fmt.Println("Unable to detach role policy to role")
        return
    }
    fmt.Println("Role detached successfully")
```

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

# Working with IAM Server Certificates
<a name="iam-example-server-certificates"></a>

This Go example shows you how to carry out basic tasks for managing server certificate HTTPS connections with the AWS SDK for Go.

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/iam) repository on GitHub.

## Scenario
<a name="iam-certificates-scenario"></a>

To enable HTTPS connections to your website or application on AWS, you need an SSL/TLS server certificate. To use a certificate that you obtained from an external provider with your website or application on AWS, you must upload the certificate to IAM or import it into AWS Certificate Manager.

In this example, you use a series of Go routines to manage policies in IAM. The routines use the AWS SDK for GoIAM client methods that follow:
+  [ListServerCertificates](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListServerCertificates) 
+  [GetServerCertificate](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetServerCertificate) 
+  [UpdateServerCertificate](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.UpdateServerCertificate) 
+  [DeleteServerCertificate](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteServerCertificate) 

## Prerequisites
<a name="iam-certificates-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with server certificates. To learn more, see [Working with Server Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) in the IAM User Guide.

## List Your Server Certificates
<a name="iam-example-list-certificates"></a>

This code lists your certificates. Create a new Go file named `iam_listservercerts.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"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up the session and IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `ListServerCertificates` and print the details.

```
    result, err := svc.ListServerCertificates(nil)
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    for i, metadata := range result.ServerCertificateMetadataList {
        if metadata == nil {
            continue
        }

        fmt.Printf("Metadata %d: %v\n", i, metadata)
    }
```

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

## Get a Server Certificate
<a name="iam-example-get-certificate"></a>

In this example, you retrieve an existing server certificate.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `GetServerCertificate`, passing the name of the certificate, and print the results.

```
    result, err := svc.GetServerCertificate(&iam.GetServerCertificateInput{
        ServerCertificateName: aws.String("CERTIFICATE_NAME"),
    })
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("ServerCertificate:", result)
}
```

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

## Update a Server Certificate
<a name="iam-example-update-certificate"></a>

In this example, you update an existing server certificate.

Create a new Go file named `iam_updateservercert.go`. You call the `UpdateServerCertificate` method of the IAM service object to change the name of the certificate.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Update the certificate name.

```
    _, err = svc.UpdateServerCertificate(&iam.UpdateServerCertificateInput{
        ServerCertificateName:    aws.String("CERTIFICATE_NAME"),
        NewServerCertificateName: aws.String("NEW_CERTIFICATE_NAME"),
    })
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Server certificate updated")
}
```

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

## Delete a Server Certificate
<a name="iam-example-delete-server-certificate"></a>

In this example, you delete an existing server certificate.

Create a new Go file named `iam_deleteservercert.go`. You call the `DeleteServerCertificate` method of the IAM service object to change the name of the certificate.

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

```
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/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call the method to delete the certificate, specifying the name of certificate.

```
    _, err = svc.DeleteServerCertificate(&iam.DeleteServerCertificateInput{
        ServerCertificateName: aws.String("CERTIFICATE_NAME"),
    })
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Server certificate deleted")
}
```

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

# AWS Key Management Service Examples Using the AWS SDK for Go
<a name="using-kms-with-go-sdk"></a>

You can use the following examples to access AWS Key Management Service (AWS KMS) using the AWS SDK for Go. For more information about AWS KMS, see the [AWS KMS documentation](https://aws.amazon.com/documentation/kms/). For reference information about the AWS KMS client, see the [New](https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#New) function.

 **Examples** 

**Topics**
+ [Creating a CMK in AWS Key Management Service](kms-example-create-key.md)
+ [Encrypting Data with AWS Key Management Service](kms-example-encrypt-data.md)
+ [Decrypting a Data Blob in AWS Key Management Service](kms-example-decrypt-blob.md)
+ [Re-encrypting a Data Blob in AWS Key Management Service](kms-example-re-encrypt-data.md)

# Creating a CMK in AWS Key Management Service
<a name="kms-example-create-key"></a>

The following example uses the AWS SDK for Go[CreateKey](https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#KMS.CreateKey) method, which implements the [CreateKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_CreateKey.html) operation, to create a customer master key (CMK). Since the example only encrypts a small amount of data, a CMK is fine for our purposes. For larger amounts of data, use the CMK to encrypt a data encryption key (DEK).

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/kms"

    "fmt"
    "os"
)

// Create an AWS KMS key (KMS key)
// Since we are only encrypting small amounts of data (4 KiB or less) directly,
// a KMS key is fine for our purposes.
// For larger amounts of data,
// use the KMS key to encrypt a data encryption key (DEK).

func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create KMS service client
    svc := kms.New(sess)

    // Create the key
    result, err := svc.CreateKey(&kms.CreateKeyInput{
        Tags: []*kms.Tag{
            {
                TagKey:   aws.String("CreatedBy"),
                TagValue: aws.String("ExampleUser"),
            },
        },
    })

    if err != nil {
        fmt.Println("Got error creating key: ", err)
        os.Exit(1)
    }

    fmt.Println(*result.KeyMetadata.KeyId)
}
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/kms/kms_create_key.go) on GitHub.

# Encrypting Data with AWS Key Management Service
<a name="kms-example-encrypt-data"></a>

The following example uses the AWS SDK for Go[Encrypt](https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#KMS.Encrypt) method, which implements the [Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) operation, to encrypt the string “1234567890”. The example displays a readable version of the resulting encrypted blob.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/kms"

    "fmt"
    "os"
)

func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create KMS service client
    svc := kms.New(sess)

    // Encrypt data key
    //
    // Replace the fictitious key ARN with a valid key ID

    keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"

    text := "1234567890"

    // Encrypt the data
    result, err := svc.Encrypt(&kms.EncryptInput{
        KeyId: aws.String(keyId),
        Plaintext: []byte(text),
    })

    if err != nil {
        fmt.Println("Got error encrypting data: ", err)
        os.Exit(1)
    }

    fmt.Println("Blob (base-64 byte array):")
    fmt.Println(result.CiphertextBlob)
}
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/kms/kms_encrypt_data.go) on GitHub.

# Decrypting a Data Blob in AWS Key Management Service
<a name="kms-example-decrypt-blob"></a>

The following example uses the AWS SDK for Go[Decrypt](https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#KMS.Decrypt) method, which implements the [Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) operation, to decrypt the provided string and emits the result.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/kms"

    "fmt"
    "os"
)

func main() {
    // Initialize a session that the SDK uses to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and configuration from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create KMS service client
    svc := kms.New(sess)

    // Encrypted data
    blob := []byte("1234567890")

    // Decrypt the data
    result, err := svc.Decrypt(&kms.DecryptInput{CiphertextBlob: blob})

    if err != nil {
        fmt.Println("Got error decrypting data: ", err)
        os.Exit(1)
    }

    blob_string := string(result.Plaintext)

    fmt.Println(blob_string)
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/kms/kms_decrypt_data.go) on GitHub.

# Re-encrypting a Data Blob in AWS Key Management Service
<a name="kms-example-re-encrypt-data"></a>

The following example uses the AWS SDK for Go[ReEncrypt](https://docs.aws.amazon.com/sdk-for-go/api/service/kms/#KMS.ReEncrypt) method, which implements the [ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html) operation, to decrypt encrypted data and then immediately re-encrypt data under a new customer master key (CMK). The operations are performed entirely on the server side within AWS KMS, so they never expose your plaintext outside of AWS KMS. The example displays a readable version of the resulting re-encrypted blob.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/kms"

    "fmt"
    "os"
)

func main() {
    // Initialize a session that the SDK uses to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and configuration from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create KMS service client
    svc := kms.New(sess)

    // Encrypt data key
    //
    // Replace the fictitious key ARN with a valid key ID

    keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"

    // Encrypted data
    blob := []byte("1234567890")

    // Re-encrypt the data key
    result, err := svc.ReEncrypt(&kms.ReEncryptInput{CiphertextBlob: blob, DestinationKeyId: &keyId})

    if err != nil {
        fmt.Println("Got error re-encrypting data: ", err)
        os.Exit(1)
    }

    fmt.Println("Blob (base-64 byte array):")
    fmt.Println(result.CiphertextBlob)
```

Choose `Copy` to save the code locally. See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/kms/kms_re_encrypt_data.go) on GitHub.

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

AWS Lambda (Lambda) is a zero-administration compute platform for backend web developers that runs your code for you in the AWS Cloud, and provides you with a fine-grained pricing structure. You can use the following examples to access AWS Lambda (Lambda) using the AWS SDK for Go. For more information about Lambda, see the [Lambda documentation](https://aws.amazon.com/documentation/lambda/).

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/lambda) repository on GitHub.

**Topics**
+ [Displaying Information about All Lambda Functions](lambda-go-example-show-functions.md)
+ [Creating a Lambda Function](lambda-go-example-create-function.md)
+ [Running a Lambda Function](lambda-go-example-run-function.md)
+ [Configuring a Lambda Function to Receive Notifications](lambda-go-example-configure-function-for-notification.md)

# Displaying Information about All Lambda Functions
<a name="lambda-go-example-show-functions"></a>

First import the packages we use in this example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/lambda"

    "fmt"
    "os"
)
```

Next, create the session and Lambda client.

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

svc := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")})
```

Next, call `ListFunctions` and exit if there is an error.

```
result, err := svc.ListFunctions(nil)
if err != nil {
    fmt.Println("Cannot list functions")
    os.Exit(0)
}
```

Finally, display the names and descriptions of the Lambda functions.

```
fmt.Println("Functions:")

for _, f := range result.Functions {
    fmt.Println("Name:        " + aws.StringValue(f.FunctionName))
    fmt.Println("Description: " + aws.StringValue(f.Description))
    fmt.Println("")
}
```

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

# Creating a Lambda Function
<a name="lambda-go-example-create-function"></a>

The following example creates the Lambda function `functionName` in the `us-west-2` region using the following values:
+ Role ARN: `resourceArn`. In most cases, you need to attach only the `AWSLambdaExecute` managed policy to the policy for this role.
+ Function entry point: `handler` 
+ Runtime: `runtime` 
+ Zip file: `zipFileName` \$1 `.zip` 
+ Bucket: `amzn-s3-demo-bucket` 
+ Key: `zipFileName` 

The first step is to import the packages we use in the example.

```
import (
    "flag"
    "fmt"
    "io/ioutil"

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

Get the zip file name, bucket name, function name, handler, ARN, and runtime values from the command line. If any are missing, print and error message and quit.

```
zipFile := flag.String("z", "", "The name of the ZIP file, without the .zip extension.")
bucket := flag.String("b", "", "the name of bucket to which the ZIP file is uploaded.")
function := flag.String("f", "", "The name of the Lambda function.")
handler := flag.String("h", "main", "The name of the package.class handling the call.")
roleARN := flag.String("a", "", "The ARN of the role that calls the function.")
runtime := flag.String("r", "go1.x", "The runtime for the function.")

flag.Parse()

if *zipFile == "" || *bucket == "" || *function == "" || *handler == "" || *roleARN == "" || *runtime == "" {
    fmt.Println("You must supply a zip file name, bucket name, function name, handler (package) name, role ARN, and runtime value.")
    return
}
```

Create the session and Lambda client and get the contents of the zip file. If you cannot read the zip file contents, print an error message and quit.

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

Next, create the structures for the input argument to the `CreateFunction` function.

```
createCode := &lambda.FunctionCode{
    //      S3Bucket:        bucket,
    //      S3Key:           zipFile,
    //      S3ObjectVersion: aws.String("1"),
    ZipFile: contents,
}

createArgs := &lambda.CreateFunctionInput{
    Code:         createCode,
    FunctionName: function,
    Handler:      handler,
    Role:         role,
    Runtime:      runtime,
}
```

Finally, call `CreateFunction` and display a message with the result of the call.

```
result, err := svc.CreateFunction(createArgs)
```

# Running a Lambda Function
<a name="lambda-go-example-run-function"></a>

The following example runs the Lambda function `MyGetitemsFunction` in the `us-west-2` region. This Node.js function returns a list of items from a database. The input JSON looks like the following.

```
{
   "SortBy": "name|time",
   "SortOrder": "ascending|descending",
   "Number": 50
}
```

Where:
+  `SortBy` is the criteria for sorting the results. Our example uses `time`, which means the returned items are sorted in the order in which they were added to the database.
+  `SortOrder` is the order of sorting. Our example uses `descending`, which means the most-recent item is last in the list.
+  `Number` is the maximum number of items to retrieve (the default is 50). Our example uses `10`, which means get the 10 most-recent items.

The output JSON looks like the following when the function succeeds and two items are returned.

```
{
   "statusCode": 200,
   "body": {
      "result": "success",
      "error": ""
      "data": [
         {
            "item": "item1"
         },
         {
            "item": "item2"
         }
      ]
   }
}
```

Where:
+  `statusCode`– An HTTP status code; `200` means the call was successful.
+  `body`– The body of the returned JSON.
+  `result`– The result of the call, either `success` or `failure`.
+  `error`– An error message if `result` is `failure`; otherwise, an empty string.
+  `data`– The returned results if `result` is `success`; otherwise, nil.
+  `item`– An item from the list of results.

The first step is to import the packages we use.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/lambda"
    
    "encoding/json"
    "fmt"
    "os"
    "strconv"
)
```

Next create session and Lambda client we use to invoke the Lambda function.

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

client := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")})
```

Next, create the request and payload, and call `MyGetItemsFunction`. If there is an error, display a message and quit.

```
request := getItemsRequest{"time", "descending", 10}

payload, err := json.Marshal(request)
if err != nil {
    fmt.Println("Error marshalling MyGetItemsFunction request")
    os.Exit(0)
}

result, err := client.Invoke(&lambda.InvokeInput{FunctionName: aws.String("MyGetItemsFunction"), Payload: payload})
if err != nil {
    fmt.Println("Error calling MyGetItemsFunction")
    os.Exit(0)
}
```

Finally, parse the response, and if successful, print out the items.

```
var resp getItemsResponse

err = json.Unmarshal(result.Payload, &resp)
if err != nil {
    fmt.Println("Error unmarshalling MyGetItemsFunction response")
    os.Exit(0)
}

// If the status code is NOT 200, the call failed
if resp.StatusCode != 200 {
    fmt.Println("Error getting items, StatusCode: " + strconv.Itoa(resp.StatusCode))
    os.Exit(0)
}

// If the result is failure, we got an error
if resp.Body.Result == "failure" {
    fmt.Println("Failed to get items")
    os.Exit(0)
}

// Print out items
if len(resp.Body.Data) > 0 {
    for i := range resp.Body.Data {
        fmt.Println(resp.Body.Data[i].Item)
    }
} else {
    fmt.Println("There were no items")
}
```

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

**Note**  
The [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go) includes the structures for marshaling the JSON request and unmarshaling the JSON response.

# Configuring a Lambda Function to Receive Notifications
<a name="lambda-go-example-configure-function-for-notification"></a>

The following example configures the Lambda function `functionName` to accept notifications from the resource with the ARN `sourceArn`.

Import the packages we use.

```
import (
    "flag"
    "fmt"
    "os"

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

Get the name of the function and ARN of the entity invoking the function. If either is missing, print an error message and quit.

```
functionPtr := flag.String("f", "", "The name of the Lambda function")
sourcePtr := flag.String("a", "", "The ARN of the entity invoking the function")
flag.Parse()

if *functionPtr == "" || *sourcePtr == "" {
    fmt.Println("You must supply the name of the function and of the entity invoking the function")
    flag.PrintDefaults()
    os.Exit(1)
}
```

Create the session and Lambda client.

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

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

Create the structure for the input argument to the `AddPermission` function.

```
permArgs := &lambda.AddPermissionInput{
    Action:       aws.String("lambda:InvokeFunction"),
    FunctionName: functionPtr,
    Principal:    aws.String("s3.amazonaws.com"),
    SourceArn:    sourcePtr,
    StatementId:  aws.String("lambda_s3_notification"),
}
```

Finally, call `AddPermission` and display a message with the result of the call.

```
result, err := svc.AddPermission(permArgs)
if err != nil {
    fmt.Println("Cannot configure function for notifications")
    os.Exit(0)
}

fmt.Println(result)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/lambda/aws-go-sdk-lambda-example-configure-function-for-notification.go) on GitHub.

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

Amazon Polly is a cloud service that converts text into lifelike speech. The AWS SDK for Go examples can integrate Amazon Polly 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/polly) repository on GitHub.

**Topics**
+ [Getting a List of Voices](polly-example-describe-voices.md)
+ [Getting a List of Lexicons](polly-example-list-lexicons.md)
+ [Synthesizing Speech](polly-example-synthesize-speech.md)

# Getting a List of Voices
<a name="polly-example-describe-voices"></a>

This example uses the [DescribeVoices](https://docs.aws.amazon.com/sdk-for-go/api/service/polly/#Polly.DescribeVoices) operation to get the list of voices in the `us-west-2` region.

Choose `Copy` to save the code locally.

Create the file *pollyDescribeVoices.go*. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/polly"

    "fmt"
    "os"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create an Amazon Polly client.

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

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

Create the input for and call `DescribeVoices`.

```
input := &polly.DescribeVoicesInput{LanguageCode: aws.String("en-US")}
resp, err := svc.DescribeVoices(input)
```

Display the name and gender of the voices.

```
for _, v := range resp.Voices {
    fmt.Println("Name:   " + *v.Name)
    fmt.Println("Gender: " + *v.Gender)
    fmt.Println("")
}
```

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

# Getting a List of Lexicons
<a name="polly-example-list-lexicons"></a>

This example uses the [ListLexicons](https://docs.aws.amazon.com/sdk-for-go/api/service/polly/#Polly.ListLexicons) operation to get the list of lexicons in the `us-west-2` region.

Choose `Copy` to save the code locally.

Create the file *pollyListLexicons.go*. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/polly"

    "fmt"
    "os"
)
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create an Amazon Polly client.

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

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

Call `ListLexicons` and display the name, alphabet, and language code of each lexicon.

```
resp, err := svc.ListLexicons(nil)

for _, l := range resp.Lexicons {
    fmt.Println(*l.Name)
    fmt.Println("  Alphabet: " + *l.Attributes.Alphabet)
    fmt.Println("  Language: " + *l.Attributes.LanguageCode)
    fmt.Println("")
}
```

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

# Synthesizing Speech
<a name="polly-example-synthesize-speech"></a>

This example uses the [SynthesizeSpeech](https://docs.aws.amazon.com/sdk-for-go/api/service/polly/#Polly.SynthesizeSpeech) operation to get the text from a file and produce an MP3 file containing the synthesized speech.

Choose `Copy` to save the code locally.

Create the file *pollySynthesizeSpeech.go*. Import the packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/polly"

    "fmt"
    "os"
    "strings"
    "io"
    "io/ioutil"
)
```

Get the name of the text file from the command line.

```
if len(os.Args) != 2 {
    fmt.Println("You must supply an alarm name")
    os.Exit(1)
}

fileName := os.Args[1]
```

Open the text file and read the contents as a string.

```
contents, err := ioutil.ReadFile(fileName)
s := string(contents[:])
```

Initialize a session that the SDK will use to load credentials from the shared credentials file `~/.aws/credentials`, load your configuration from the shared configuration file `~/.aws/config`, and create an Amazon Polly client.

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

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

Create the input for and call `SynthesizeSpeech`.

```
input := &polly.SynthesizeSpeechInput{OutputFormat: aws.String("mp3"), Text: aws.String(s), VoiceId: aws.String("Joanna")}

output, err := svc.SynthesizeSpeech(input)
```

Save the resulting synthesized speech as an MP3 file.

```
names := strings.Split(fileName, ".")
name := names[0]
mp3File := name + ".mp3"

outFile, err := os.Create(mp3File)
defer outFile.Close()
```

**Note**  
The resulting MP3 file is in the MPEG-2 format.

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

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

Amazon Simple Storage Service (Amazon S3) is storage for the internet. The AWS SDK for Go examples can integrate Amazon S3 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/s3) repository on GitHub.

**Topics**
+ [Performing Basic Amazon S3 Bucket Operations](s3-example-basic-bucket-operations.md)
+ [Creating Pre-Signed URLs for Amazon S3 Buckets](s3-example-presigned-urls.md)
+ [Using an Amazon S3 Bucket as a Static Web Host](s3-example-static-web-host.md)
+ [Working with Amazon S3 CORS Permissions](s3-example-cors.md)
+ [Working with Amazon S3 Bucket Policies](s3-example-bucket-policy.md)
+ [Working with Amazon S3 Bucket ACLs](s3-example-bucket-acls.md)
+ [Encrypting Amazon S3 Bucket Items](s3-examples-encryption.md)

# Performing Basic Amazon S3 Bucket Operations
<a name="s3-example-basic-bucket-operations"></a>

These AWS SDK for Go examples show you how to perform the following operations on Amazon S3 buckets and bucket items:
+ List the buckets in your account
+ Create a bucket
+ List the items in a bucket
+ Upload a file to a bucket
+ Download a bucket item
+ Copy a bucket item to another bucket
+ Delete a bucket item
+ Delete all the items in a bucket
+ Restore a bucket item
+ Delete a bucket
+ List the users with administrator privileges

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/s3) repository on GitHub.

## Scenario
<a name="s3-examples-bucket-ops-scenario"></a>

In these examples, a series of Go routines are used to perform operations on your Amazon S3 buckets. The routines use the AWS SDK for Go to perform Amazon S3 bucket operations using the following methods of the Amazon S3 client class, unless otherwise noted:
+  [ListBuckets](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListBuckets) 
+  [CreateBucket](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CreateBucket) 
+  [ListObjects](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListObjects) 
+  [Upload](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Uploader.Upload) (from the **s3manager.NewUploader** class)
+  [Download](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Downloader.Download) (from the **s3manager.NewDownloader** class)
+  [CopyObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CopyObject) 
+  [DeleteObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteObject) 
+  [DeleteObjects](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteObjects) 
+  [RestoreObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.RestoreObject) 
+  [DeleteBucket](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteBucket) 

## Prerequisites
<a name="s3-examples-bucket-ops-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with buckets. To learn more, see [Working with Amazon S3 Buckets](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html) in the Amazon S3 Developer Guide.

## List Buckets
<a name="s3-examples-bucket-ops-list-buckets"></a>

The [ListBuckets](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListBuckets) function lists the buckets in your account.

The following example lists the buckets in your account. There are no command line arguments.

Create the file *s3\$1list\$1buckets.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [ListBuckets](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListBuckets). Passing `nil` means no filters are applied to the returned list. If an error occurs, call `exitErrorf`. If no error occurs, loop through the buckets, printing the name and creation date of each bucket.

```
result, err := svc.ListBuckets(nil)
if err != nil {
    exitErrorf("Unable to list buckets, %v", err)
}

fmt.Println("Buckets:")

for _, b := range result.Buckets {
    fmt.Printf("* %s created on %s\n",
        aws.StringValue(b.Name), aws.TimeValue(b.CreationDate))
}
```

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

## Create a Bucket
<a name="s3-examples-bucket-ops-create-bucket"></a>

The [CreateBucket](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CreateBucket) function creates a bucket in your account.

The following example creates a bucket with the name specified as a command line argument. You must specify a globally unique name for the bucket.

Create the file *s3\$1create\$1bucket.go*. Import the following Go and AWS SDK for Go packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

The program requires one argument, the name of the bucket to create.

```
if len(os.Args) != 2 {
    exitErrorf("Bucket name missing!\nUsage: %s bucket_name", os.Args[0])
}

bucket := os.Args[1]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [CreateBucket](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CreateBucket), passing in the bucket name defined previously. If an error occurs, call `exitErrorf`. If there are no errors, wait for a notification that the bucket was created.

```
_, err = svc.CreateBucket(&s3.CreateBucketInput{
    Bucket: aws.String(bucket),
})
if err != nil {
    exitErrorf("Unable to create bucket %q, %v", bucket, err)
}

// Wait until bucket is created before finishing
fmt.Printf("Waiting for bucket %q to be created...\n", bucket)

err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{
    Bucket: aws.String(bucket),
})
```

If the `WaitUntilBucketExists` call returns an error, call `exitErrorf`. If there are no errors, notify the user of success.

```
if err != nil {
    exitErrorf("Error occurred while waiting for bucket to be created, %v", bucket)
}

fmt.Printf("Bucket %q successfully created\n", bucket)
```

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

## List Bucket Items
<a name="s3-examples-bucket-ops-list-bucket-items"></a>

The [ListObjects](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListObjects) function lists the items in a bucket.

The following example lists the items in the bucket with the name specified as a command line argument.

Create the file *s3\$1list\$1objects.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

The program requires one command line argument, the name of the bucket.

```
if len(os.Args) != 2 {
    exitErrorf("Bucket name required\nUsage: %s bucket_name",
        os.Args[0])
}

bucket := os.Args[1]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [ListObjects](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.ListObjects), passing in the name of the bucket. If an error occurs, call `exitErrorf`. If no error occurs, loop through the items, printing the name, last modified date, size, and storage class of each item.

```
resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: aws.String(bucket)})
if err != nil {
    exitErrorf("Unable to list items in bucket %q, %v", bucket, err)
}

for _, item := range resp.Contents {
    fmt.Println("Name:         ", *item.Key)
    fmt.Println("Last modified:", *item.LastModified)
    fmt.Println("Size:         ", *item.Size)
    fmt.Println("Storage class:", *item.StorageClass)
    fmt.Println("")
}
```

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

## Upload a File to a Bucket
<a name="s3-examples-bucket-ops-upload-file-to-bucket"></a>

The [Upload](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Uploader.Upload) function uploads an object to a bucket.

The following example uploads a file to a bucket with the names specified as command line arguments.

Create the file *s3\$1upload\$1object.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

Get the bucket and file name from the command line arguments, open the file, and defer the file closing until we are done with it. If an error occurs, call `exitErrorF`.

```
if len(os.Args) != 3 {
    exitErrorf("bucket and file name required\nUsage: %s bucket_name filename",
        os.Args[0])
}

bucket := os.Args[1]
filename := os.Args[2]

file, err := os.Open(filename)
if err != nil {
    exitErrorf("Unable to open file %q, %v", err)
}

defer file.Close()
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a `NewUploader` object.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Setup the S3 Upload Manager. Also see the SDK doc for the Upload Manager
// for more information on configuring part size, and concurrency.
//
// http://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#NewUploader
uploader := s3manager.NewUploader(sess)
```

Upload the file to the bucket. If an error occurs, call `exitErrorF`. Otherwise, notify the user that the upload succeeded.

```
_, err = uploader.Upload(&s3manager.UploadInput{
    Bucket: aws.String(bucket),
    Key: aws.String(filename),
    Body: file,
})
if err != nil {
    // Print the error and exit.
    exitErrorf("Unable to upload %q to %q, %v", filename, bucket, err)
}

fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket)
```

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

## Download a File from a Bucket
<a name="s3-examples-bucket-ops-download-file-from-bucket"></a>

The [Download](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Downloader.Download) function downloads an object from a bucket.

The following example downloads an item from a bucket with the names specified as command line arguments.

Create the file *s3\$1download\$1object.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
    
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

Get the bucket and file name from the command line arguments. If there aren’t two arguments, call `exitErrorf`. Otherwise, create the file and defer file closing until we are done downloading. If an error occurs while creating the file, call `exitErrorf`.

```
if len(os.Args) != 3 {
    exitErrorf("Bucket and item names required\nUsage: %s bucket_name item_name",
        os.Args[0])
}

bucket := os.Args[1]
item := os.Args[2]
```

Initialize the session in us-west-2 that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a `NewDownloader` object.

```
sess, _ := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

downloader := s3manager.NewDownloader(sess)
```

Download the item from the bucket. If an error occurs, call `exitErrorf`. Otherwise, notify the user that the download succeeded.

```
numBytes, err := downloader.Download(file,
    &s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(item),
    })
if err != nil {
    exitErrorf("Unable to download item %q, %v", item, err)
}

fmt.Println("Downloaded", file.Name(), numBytes, "bytes")
```

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

## Copy an Item from one Bucket to Another
<a name="s3-examples-bucket-ops-copy-bucket-item"></a>

The [CopyObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CopyObject) function copies an object from one bucket to another.

The following example copies an item from one bucket to another with the names specified as command line arguments.

Create the file *s3\$1copy\$1object.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "net/url"
    "os"
)
```

Create a function we use to display errors and exit.

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

Get the names of the bucket containing the item, the item to copy, and the name of the bucket to which the item is copied. If there aren’t four command line arguments, call `exitErrorf`.

```
if len(os.Args) != 4 {
    exitErrorf("Bucket, item, and other bucket names required\nUsage: go run s3_copy_object bucket item other-bucket")
}

bucket := os.Args[1]
item := os.Args[2]
other := os.Args[3]

source := bucket + "/" + item
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [CopyObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.CopyObject), with the names of the bucket containing the item, the item to copy, and the name of the bucket to which the item is copied. If an error occurs, call `exitErrorf`. If no error occurs, wait for the item to be copied.

```
// Copy the item
_, err = svc.CopyObject(&s3.CopyObjectInput{Bucket: aws.String(other),
    CopySource: aws.String(url.PathEscape(source)), Key: aws.String(item)})
if err != nil {
    exitErrorf("Unable to copy item from bucket %q to bucket %q, %v", bucket, other, err)
}
```

If the `WaitUntilObjectExists` call returns an error, call `exitErrorf`. Otherwise, notify the user that the copy succeeded.

```
// Wait to see if the item got copied
err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{Bucket: aws.String(other), Key: aws.String(item)})
if err != nil {
    exitErrorf("Error occurred while waiting for item %q to be copied to bucket %q, %v", bucket, item, other, err)
}

fmt.Printf("Item %q successfully copied from bucket %q to bucket %q\n", item, bucket, other)
```

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

## Delete an Item in a Bucket
<a name="s3-examples-bucket-ops-delete-bucket-item"></a>

The [DeleteObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteObject) function deletes an object from a bucket.

The following example deletes an item from a bucket with the names specified as command line arguments.

Create the file *s3\$1delete\$1object.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

Get the name of the bucket and object to delete.

```
if len(os.Args) != 3 {
    exitErrorf("Bucket and object name required\nUsage: %s bucket_name object_name",
        os.Args[0])
}

bucket := os.Args[1]
obj := os.Args[2]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [DeleteObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteObject), passing in the names of the bucket and object to delete. If an error occurs, call `exitErrorf`. If no error occurs, wait until the object is deleted.

```
_, err = svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj)})
if err != nil {
    exitErrorf("Unable to delete object %q from bucket %q, %v", obj, bucket, err)
}

err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{
    Bucket: aws.String(bucket),
    Key:    aws.String(obj),
})
```

If `WaitUntilObjectNotExists` returns an error, call `exitErrorf`. Otherwise, inform the user that the object was successfully deleted.

```
fmt.Printf("Object %q successfully deleted\n", obj)
```

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

## Delete All the Items in a Bucket
<a name="s3-examples-bucket-ops-delete-all-bucket-items"></a>

The [DeleteObjects](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteObjects) function deletes objects from a bucket.

The following example deletes all the items from a bucket with the bucket name specified as a command line argument.

Create the file *s3\$1delete\$1objects.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/aws/aws-sdk-go/service/s3/s3manager"
    
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

Get the name of the bucket.

```
if len(os.Args) != 2 {
    exitErrorf("Bucket name required\nUsage: %s BUCKET", os.Args[0])
}

bucket := os.Args[1]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

```
sess, _ := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)
svc := s3.New(sess)
```

Create a list iterator to iterate through the list of bucket objects, deleting each object. If an error occurs, call `exitErrorf`.

```
iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{
    Bucket: aws.String(bucket),
})

if err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter); err != nil {
    exitErrorf("Unable to delete objects from bucket %q, %v", bucket, err)
}
```

Once all of the items in the bucket have been deleted, inform the user that the objects were deleted.

```
fmt.Printf("Deleted object(s) from bucket: %s", bucket)
```

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

## Restore a Bucket Item
<a name="s3-examples-bucket-ops-restore-bucket-item"></a>

The [RestoreObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.RestoreObject) function restores an item in a bucket.

The following example restores the items in a bucket with the names specified as command line arguments.

Create the file *s3\$1restore\$1object.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

The program requires two arguments, the names of the bucket and object to restore.

```
if len(os.Args) != 3 {
    exitErrorf("Bucket name and object name required\nUsage: %s bucket_name object_name",
        os.Args[0])
}

bucket := os.Args[1]
obj := os.Args[2]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [RestoreObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.RestoreObject), passing in the bucket and object names and the number of days to temporarily restore. If an error occurs, call `exitErrorf`. Otherwise, inform the user that the bucket should be restored in the next four hours or so.

```
_, err = svc.RestoreObject(&s3.RestoreObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj), RestoreRequest: &s3.RestoreRequest{Days: aws.Int64(30)}})
if err != nil {
    exitErrorf("Could not restore %s in bucket %s, %v", obj, bucket, err)
}

fmt.Printf("%q should be restored to %q in about 4 hours\n", obj, bucket)
```

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

## Delete a Bucket
<a name="s3-examples-bucket-ops-delete-bucket"></a>

The [DeleteBucket](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteBucket) function deletes a bucket.

The following example deletes the bucket with the name specified as a command line argument.

Create the file *s3\$1delete\$1bucket.go*. Import the following Go and AWS SDK for Go packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
)
```

Create a function we use to display errors and exit.

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

The program requires one argument, the name of the bucket to delete. If the argument is not supplied, call `exitErrorf`.

```
if len(os.Args) != 2 {
    exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0])
}

bucket := os.Args[1]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [DeleteBucket](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteBucket), passing in the bucket name. If an error occurs, call `exitErrorf`. If there are no errors, wait for a notification that the bucket was deleted.

```
_, err = svc.DeleteBucket(&s3.DeleteBucketInput{
    Bucket: aws.String(bucket),
})
if err != nil {
    exitErrorf("Unable to delete bucket %q, %v", bucket, err)
}

// Wait until bucket is deleted before finishing
fmt.Printf("Waiting for bucket %q to be deleted...\n", bucket)

err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{
    Bucket: aws.String(bucket),
})
```

If `WaitUntilBucketNotExists` returns an error, call `exitErrorf`. Otherwise, inform the user that the bucket was successfully deleted.

```
if err != nil {
    exitErrorf("Error occurred while waiting for bucket to be deleted, %v", bucket)
}

fmt.Printf("Bucket %q successfully deleted\n", bucket)
```

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

# Creating Pre-Signed URLs for Amazon S3 Buckets
<a name="s3-example-presigned-urls"></a>

This Go example shows you how to obtain a pre-signed URL for an Amazon S3 bucket. 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/s3) repository on GitHub.

## Scenario
<a name="s3-pre-signed-scenario"></a>

In this example, a series of Go routines are used to obtain a pre-signed URL for an Amazon S3 bucket using either GetObject or a PUT operation. A pre-signed URL allows you to grant temporary access to users who don’t have permission to directly run AWS operations in your account. A pre-signed URL is signed with your credentials and can be used by any user.
+  [Presign](https://docs.aws.amazon.com/sdk-for-go/api/aws/request/#Request.Presign) 

## Prerequisites
<a name="s3-pre-signed-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the SDK.
+ You are familiar with pre-signed URLs. To learn more, see [Uploading Objects Using Pre-Signed URLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html) in the Amazon S3 Developer Guide.

## Generate a Pre-Signed URL for a GetObject Operation
<a name="generate-a-pre-signed-url"></a>

To generate a pre-signed URL, use the [Presign](https://docs.aws.amazon.com/sdk-for-go/api/aws/request/#Request.Presign) method on the `request` object. You must set an expiration value because the AWS SDK for Go doesn’t set one by default.

The following example generates a pre-signed URL that enables you to temporarily share a file without making it public. Anyone with access to the URL can view the file.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "log"
    "time"
)

// Downloads an item from an S3 Bucket
//
// Usage:
//    go run s3_download.go
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create S3 service client
    svc := s3.New(sess)

    req, _ := svc.GetObjectRequest(&s3.GetObjectInput{
        Bucket: aws.String("amzn-s3-demo-bucket"),
        Key:    aws.String("myKey"),
    })
    urlStr, err := req.Presign(15 * time.Minute)

    if err != nil {
        log.Println("Failed to sign request", err)
    }

    log.Println("The URL is", urlStr)
}
```

If the SDK has not retrieved your credentials before calling `Presign`, it will get them to generate the pre-signed URL.

## Generate a Pre-Signed URL for an Amazon S3 PUT Operation with a Specific Payload
<a name="generate-a-pre-signed-url-put"></a>

You can generate a pre-signed URL for a PUT operation that checks whether users upload the correct content. When the SDK pre-signs a request, it computes the checksum of the request body and generates an MD5 checksum that is included in the pre-signed URL. Users must upload the same content that produces the same MD5 checksum generated by the SDK; otherwise, the operation fails. This is not the Content-MD5, but the signature. To enforce Content-MD5, simply add the header to the request.

The following example adds a `Body` field to generate a pre-signed PUT operation that requires a specific payload to be uploaded by users.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "log"
    "strings"
    "time"
)

func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create S3 service client
    svc := s3.New(sess)

    req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String("amzn-s3-demo-bucket"),
        Key:    aws.String("myKey"),
        Body:   strings.NewReader("EXPECTED CONTENTS"),
    })
    str, err := req.Presign(15 * time.Minute)

    log.Println("The URL is:", str, " err:", err)
}
```

If you omit the `Body` field, users can write any contents to the given object.

The following example shows the enforcing of Content-MD5.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "encoding/base64"
    "fmt"
    "crypto/md5"
    "strings"
    "time"
    "net/http"
)

// Downloads an item from an S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
//    go run s3_download.go
func main() {
    h := md5.New()
    content := strings.NewReader("")
    content.WriteTo(h)

    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create S3 service client
    svc := s3.New(sess)

    resp, _ := svc.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String("amzn-s3-demo-bucket"),
        Key:    aws.String("testKey"),
    })

    md5s := base64.StdEncoding.EncodeToString(h.Sum(nil))
    resp.HTTPRequest.Header.Set("Content-MD5", md5s)

    url, err := resp.Presign(15 * time.Minute)
    if err != nil {
        fmt.Println("error presigning request", err)
        return
    }

    req, err := http.NewRequest("PUT", url, strings.NewReader(""))
    req.Header.Set("Content-MD5", md5s)
    if err != nil {
        fmt.Println("error creating request", url)
        return
    }

    defClient, err := http.DefaultClient.Do(req)
    fmt.Println(defClient, err)
}
```

# Using an Amazon S3 Bucket as a Static Web Host
<a name="s3-example-static-web-host"></a>

This AWS SDK for Go example shows you how to configure an Amazon S3 bucket to act as a static web host. 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/s3) repository on GitHub.

## Scenario
<a name="s3-website-scenario"></a>

In this example, you use a series of Go routines to configure any of your buckets to act as a static web host. The routines use the AWS SDK for Go to configure a selected Amazon S3 bucket using these methods of the Amazon S3 client class:
+ GetBucketWebsite
+ PutBucketWebsite
+ DeleteBucketWebsite

For more information about using an Amazon S3 bucket as a static web host, see [Hosting a Static Website on Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) in the Amazon S3 Developer Guide.

## Prerequisites
<a name="s3-website-prerequisites"></a>
+ You have [set up](setting-up.md), and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with hosting static websites on Amazon S3. To learn more, see [Hosting a Static Website on Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) in the Amazon S3 Developer Guide.

## Retrieve a Bucket’s Website Configuration
<a name="s3-example-retrieve-config"></a>

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

```
import (
    "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/s3"
    "fmt"
    "os"
)
```

This routine requires you to pass in an argument containing the name of the bucket for which you want to get website configuration.

```
if len(os.Args) != 2 {
    exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0])
}

bucket := os.Args[1]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials`, and create a new S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call [GetBucketWebsite](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketWebsite) to get the bucket configuration. You should check for the `NoSuchWebsiteConfiguration` error code, which tells you that the bucket doesn’t have a website configured.

```
result, err := svc.GetBucketWebsite(&s3.GetBucketWebsiteInput{
    Bucket: aws.String(bucket),
})
if err != nil {
    // Check for the NoSuchWebsiteConfiguration error code telling us
    // that the bucket does not have a website configured.
    if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchWebsiteConfiguration" {
        exitErrorf("Bucket %s does not have website configuration\n", bucket)
    }
    exitErrorf("Unable to get bucket website config, %v", err)
}
```

Print the bucket’s website configuration.

```
fmt.Println("Bucket Website Configuration:")
fmt.Println(result)
```

## Set a Bucket’s Website Configuration
<a name="s3-example-set-bucket-website"></a>

Create a Go file named `s3_set_bucket_website.go` and add the code below. The Amazon S3[PutBucketWebsite](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketWebsite) operation sets the website configuration on a bucket, replacing any existing configuration.

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

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
    "path/filepath"
)
```

This routine requires you to pass in an argument containing the name of the bucket and the index suffix page.

```
if len(os.Args) != 4 {
    exitErrorf("bucket name and index suffix page required\nUsage: %s bucket_name index_page [error_page]",
        filepath.Base(os.Args[0]))
}

bucket := fromArgs(os.Args, 1)
indexSuffix := fromArgs(os.Args, 2)
errorPage := fromArgs(os.Args, 3)
```

Initialize a session that the SDK will use to load configuration, credentials, and region information from the shared credentials file, `~/.aws/credentials`, and create a new S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Create the parameters to be passed in to [PutBucketWebsite](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketWebsite), including the bucket name and index document details. If the user passed in an error page when calling the routine, also add that to the parameters.

```
params := s3.PutBucketWebsiteInput{
    Bucket: aws.String(bucket),
    WebsiteConfiguration: &s3.WebsiteConfiguration{
        IndexDocument: &s3.IndexDocument{
            Suffix: aws.String(indexSuffix),
        },
    },
}

// Add the error page if set on CLI
if len(errorPage) > 0 {
    params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{
        Key: aws.String(errorPage),
    }
}
```

Call `PutBucketWebsite`, passing in the parameters you just defined. If an error occurs, print the errordetails and exit the routine.

```
_, err = svc.PutBucketWebsite(&params)
if err != nil {
    exitErrorf("Unable to set bucket %q website configuration, %v",
        bucket, err)
}

fmt.Printf("Successfully set bucket %q website configuration\n", bucket)
```

## Delete Website Configuration on a Bucket
<a name="s3-example-delete-website"></a>

Create a Go file named `s3_delete_bucket_website.go`. Import the relevant Go and AWS SDK for Go packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "fmt"
    "os"
    "path/filepath"
)
```

This routine requires you to pass in the name of the bucket for which you want to delete the website configuration.

```
if len(os.Args) != 2 {
    exitErrorf("bucket name required\nUsage: %s bucket_name",
        filepath.Base(os.Args[0]))
}

bucket := os.Args[1]
```

Initialize a session that the SDK will use to load configuration, credentials, and region information from the shared credentials file, `~/.aws/credentials`, and create a new S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create S3 service client
svc := s3.New(sess)
```

Call `DeleteBucketWebsite` and pass in the name of the bucket to complete the action.

```
_, err = svc.DeleteBucketWebsite(&s3.DeleteBucketWebsiteInput{
    Bucket: aws.String(bucket),
})
if err != nil {
    exitErrorf("Unable to delete bucket %q website configuration, %v",
        bucket, err)
}

fmt.Printf("Successfully delete bucket %q website configuration\n", bucket)
```

# Working with Amazon S3 CORS Permissions
<a name="s3-example-cors"></a>

This AWS SDK for Go example shows you how to list Amazon S3 buckets and configure CORS and bucket logging. 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/s3) repository on GitHub.

## Scenario
<a name="s3-cors-scenario"></a>

In this example, a series of Go routines are used to list your Amazon S3 buckets and to configure CORS and bucket logging. The routines use the AWS SDK for Go to configure a selected Amazon S3 bucket using these methods of the Amazon S3 client class:
+  [GetBucketCors](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketCors) 
+  [PutBucketCors](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketCors) 

If you are unfamiliar with using CORS configuration with an Amazon S3 bucket, it’s worth your time to read [Cross-Origin Resource Sharing (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html) in the Amazon S3 Developer Guide before proceeding.

## Prerequisites
<a name="s3-cors-prerequisites"></a>
+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with using CORS configuration with an Amazon S3 bucket. To learn more, see [Cross-Origin Resource Sharing (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html) in the Amazon S3 Developer Guide.

## Configure CORS on the Bucket
<a name="s3-example-cors-config"></a>

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

```
import (
    "flag"
    "fmt"
    "os"
    "strings"

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

This routine configures CORS rules for a bucket by setting the allowed HTTP methods.

It requires the bucket name and can also take a space-separated list of HTTP methods. Using the Go Language’s `flag` package, it parses the input and validates the bucket name.

```
bucketPtr := flag.String("b", "", "Bucket to set CORS on, (required)")

flag.Parse()

if *bucketPtr == "" {
    exitErrorf("-b <bucket> Bucket name required")
}

methods := filterMethods(flag.Args())
```

Notice the helper method, `filterMethods`, which ensures the methods passed in are uppercase.

```
func filterMethods(methods []string) []string {
    filtered := make([]string, 0, len(methods))
    for _, m := range methods {
        v := strings.ToUpper(m)
        switch v {
        case "POST", "GET", "PUT", "PATCH", "DELETE":
            filtered = append(filtered, v)
        }
    }

    return filtered
}
```

Initialize a session that the SDK will use to load credentials, from the shared credentials file, `~/.aws/credentials`, and create a new S3 service client.

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

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

Create a new [CORSRule](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#CORSRule) to set up the CORS configuration.

```
rule := s3.CORSRule{
    AllowedHeaders: aws.StringSlice([]string{"Authorization"}),
    AllowedOrigins: aws.StringSlice([]string{"*"}),
    MaxAgeSeconds:  aws.Int64(3000),

    // Add HTTP methods CORS request that were specified in the CLI.
    AllowedMethods: aws.StringSlice(methods),
}
```

Add the `CORSRule` to the `PutBucketCorsInput` structure, call `PutBucketCors` with that structure, and print a success or error message.

```
params := s3.PutBucketCorsInput{
    Bucket: bucketPtr,
    CORSConfiguration: &s3.CORSConfiguration{
        CORSRules: []*s3.CORSRule{&rule},
    },
}

_, err := svc.PutBucketCors(&params)
if err != nil {
    // Print the error message
    exitErrorf("Unable to set Bucket %q's CORS, %v", *bucketPtr, err)
}

// Print the updated CORS config for the bucket
fmt.Printf("Updated bucket %q CORS for %v\n", *bucketPtr, methods)
```

The example uses the following error function.

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

# Working with Amazon S3 Bucket Policies
<a name="s3-example-bucket-policy"></a>

This AWS SDK for Go example shows you how to retrieve, display, and set Amazon S3 bucket polices. 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/s3) repository on GitHub.

## Scenario
<a name="s3-bucket-policies-scenario"></a>

In this example, you use a series of Go routines to retrieve or set a bucket policy on an Amazon S3 bucket. The routines use the AWS SDK for Go to configure policy for a selected Amazon S3 bucket using these methods of the Amazon S3 client class:
+  [GetBucketPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketPolicy) 
+  [PutBucketPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketPolicy) 
+  [DeleteBucketPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.DeleteBucketPolicy) 

For more information about bucket policies for Amazon S3 buckets, see [Using Bucket Policies and User Policies](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-iam-policies.html) in the Amazon S3 Developer Guide.

## Prerequisites
<a name="s3-bucket-policies-prerequisites"></a>
+ You have [set up](setting-up.md), and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with Amazon S3 bucket polices. To learn more, see [Using Bucket Policies and User Policies](https://docs.aws.amazon.com/AmazonS3/latest/dev/using-iam-policies.html) in the Amazon S3 Developer Guide.

## Retrieve and Display a Bucket Policy
<a name="s3-example-get-policy"></a>

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

```
import (
    "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/s3"
    "bytes"
    "encoding/json"
    "fmt"
    "os"
    "path/filepath"
)
```

Create the `exitError` function to deal with errors.

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

This routine prints the policy for a bucket. If the bucket doesn’t exist, or there was an error, an error message is printed instead. It requires the bucket name as input.

```
if len(os.Args) != 2 {
    exitErrorf("bucket name required\nUsage: %s bucket_name",
        filepath.Base(os.Args[0]))
}

bucket := os.Args[1]
```

Initialize a session that the SDK will use to load credentials from the shared credentials file, `~/.aws/credentials`, and create a new S3 service client.

```
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

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

Call [GetBucketPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketPolicy) to fetch the policy, then display any errors.

```
result, err := svc.GetBucketPolicy(&s3.GetBucketPolicyInput{
    Bucket: aws.String(bucket),
})
if err != nil {
    // Special error handling for the when the bucket doesn't
    // exists so we can give a more direct error message from the CLI.
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case s3.ErrCodeNoSuchBucket:
            exitErrorf("Bucket %q does not exist.", bucket)
        case "NoSuchBucketPolicy":
            exitErrorf("Bucket %q does not have a policy.", bucket)
        }
    }
    exitErrorf("Unable to get bucket %q policy, %v.", bucket, err)
}
```

Use Go’s JSON package to print the Policy JSON returned by the call.

```
out := bytes.Buffer{}
policyStr := aws.StringValue(result.Policy)
if err := json.Indent(&out, []byte(policyStr), "", "  "); err != nil {
    exitErrorf("Failed to pretty print bucket policy, %v.", err)
}

fmt.Printf("%q's Bucket Policy:\n", bucket)
fmt.Println(out.String())
```

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

## Set Bucket Policy
<a name="s3-example-set-policy"></a>

This routine sets the policy for a bucket. If the bucket doesn’t exist, or there was an error, an error message will be printed instead. It requires the bucket name as input. It also requires the same Go and AWS SDK for Go packages as the previous example, except for the `bytes` Go package.

```
import (
    "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/s3"
    "encoding/json"
    "fmt"
    "os"
    "path/filepath"
)
```

Add the main function and parse the arguments to get the bucket name.

```
func main() {
    if len(os.Args) != 2 {
        exitErrorf("bucket name required\nUsage: %s bucket_name",
            filepath.Base(os.Args[0]))
    }
    bucket := os.Args[1]
```

Initialize a session that the SDK will use to load configuration, credentials, and region information from the shared credentials file, `~/.aws/credentials`, and create a new S3 service client.

```
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

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

Create a policy using the map interface, filling in the bucket as the resource.

```
    readOnlyAnonUserPolicy := map[string]interface{}{
        "Version": "2012-10-17",		 	 	 
        "Statement": []map[string]interface{}{
            {
                "Sid":       "AddPerm",
                "Effect":    "Allow",
                "Principal": "*",
                "Action": []string{
                    "s3:GetObject",
                },
                "Resource": []string{
                    fmt.Sprintf("arn:aws:s3:::%s/*", bucket),
                },
            },
        },
    }
```

Use Go’s JSON package to marshal the policy into a JSON value so that it can be sent to S3.

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

Call the S3 client’s [PutBucketPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketPolicy) to PUT the policy for the bucket and print the results.

```
    _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
        Bucket: aws.String(bucket),
        Policy: aws.String(string(policy)),
    })

    fmt.Printf("Successfully set bucket %q's policy\n", bucket)
```

The `exitError` function is used to deal with printing any errors.

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

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

# Working with Amazon S3 Bucket ACLs
<a name="s3-example-bucket-acls"></a>

The following examples use AWS SDK for Go functions to:
+ Get the access control lists (ACLs) on a bucket
+ Get the ACLs on a bucket item
+ Add a new user to the ACLs on a bucket
+ Add a new user to the ACLs on a bucket item

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/s3) repository on GitHub.

## Scenario
<a name="s3-examples-bucket-acls-scenario"></a>

In these examples, a series of Go routines are used to manage ACLs on your Amazon S3 buckets. The routines use the AWS SDK for Go to perform Amazon S3 bucket operations using the following methods of the Amazon S3 client class:
+  [GetBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketAcl) 
+  [GetObjectAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetObjectAcl) 
+  [PutBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketAcl) 
+  [PutObjectAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObjectAcl) 

## Prerequisites
<a name="s3-examples-bucket-acls-prerequisites"></a>
+ You have [set up](setting-up.md), and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with Amazon S3 bucket ACLs. To learn more, see [Managing Access with ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html) in the Amazon S3 Developer Guide.

## Get a Bucket ACL
<a name="s3-examples-bucket-acls-get-bucket-acl"></a>

The [GetBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketAcl) function gets the ACLs on a bucket.

The following example gets the ACLs on a bucket with the name specified as a command line argument.

Create the file *s3\$1get\$1bucket\$1acl.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    
    "fmt"
    "os"
)
```

Create a function to display errors and exit.

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

This example requires one input parameter, the name of the bucket. If the name is not supplied, call the error function and exit.

```
if len(os.Args) != 2 {
    exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET")
}

bucket := os.Args[1]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, the region from the shared configuration file `~/.aws/config`, and create a new Amazon S3 service client.

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

// Create S3 service client
svc := s3.New(sess)
```

Call [GetBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetBucketAcl), passing in the name of the bucket. If an error occurs, call `exitErrorf`. If no error occurs, loop through the results and print out the name, type, and permission for the grantees.

```
result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{Bucket: &bucket})
if err != nil {
    exitErrorf(err.Error())
}

fmt.Println("Owner:", *result.Owner.DisplayName)
fmt.Println("")
fmt.Println("Grants")

for _, g := range result.Grants {
    // If we add a canned ACL, the name is nil
    if g.Grantee.DisplayName == nil {
        fmt.Println("  Grantee:    EVERYONE")
    } else {
        fmt.Println("  Grantee:   ", *g.Grantee.DisplayName)
    }

    fmt.Println("  Type:      ", *g.Grantee.Type)
    fmt.Println("  Permission:", *g.Permission)
    fmt.Println("")
}
```

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

## Set a Bucket ACL
<a name="s3-examples-bucket-acls-set-bucket-acl"></a>

The [PutBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketAcl) function sets the ACLs on a bucket.

The following example gives a user access by email address to a bucket with the bucket name and email address specified as command line arguments. The user can also supply a permission argument. However, if it isn’o’t supplied, the user is given READ access to the bucket.

Create the file *s3\$1put\$1bucket\$1acl.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    
    "fmt"
    "os"
)
```

Create a function to display errors and exit.

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

Get the two required input parameters. If the optional permission parameter is supplied, make sure it is one of the allowed values. If not, print an error message and quit.

```
if len(os.Args) < 3 {
    exitErrorf("Bucket name and email address required; permission optional (READ if omitted)\nUsage: go run", os.Args[0], "BUCKET EMAIL [PERMISSION]")
}

bucket := os.Args[1]
address := os.Args[2]

permission := "READ"

if len(os.Args) == 4 {
    permission = os.Args[3]

    if !(permission == "FULL_CONTROL" || permission == "WRITE" || permission == "WRITE_ACP" || permission == "READ" || permission == "READ_ACP") {
        fmt.Println("Illegal permission value. It must be one of:")
        fmt.Println("FULL_CONTROL, WRITE, WRITE_ACP, READ, or READ_ACP")
        os.Exit(1)

    }
}
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, the region from the shared configuration file `~/.aws/config`, and create a new Amazon S3 service client.

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

// Create S3 service client
svc := s3.New(sess)
```

Get the existing ACLs and append the new user to the list. If there is an error while retrieving the list, print an error message and quit.

```
result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{Bucket: &bucket})
if err != nil {
    exitErrorf(err.Error())
}

owner := *result.Owner.DisplayName
ownerId := *result.Owner.ID

// Existing grants
grants := result.Grants

// Create new grantee to add to grants
var newGrantee = s3.Grantee{EmailAddress: &address, Type: &userType}
var newGrant = s3.Grant{Grantee: &newGrantee, Permission: &permission}

// Add them to the grants
grants = append(grants, &newGrant)
```

Build the parameter list for the call based on the existing ACLs and the new user information.

```
params := &s3.PutBucketAclInput{
    Bucket: &bucket,
    AccessControlPolicy: &s3.AccessControlPolicy{
        Grants: grants,
        Owner: &s3.Owner{
            DisplayName: &owner,
            ID:          &ownerId,
        },
    },
}
```

Call [PutBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketAcl), passing in the parameter list. If an error occurs, display a message and quit. Otherwise, display a message indicating success.

```
_, err = svc.PutBucketAcl(params)
if err != nil {
    exitErrorf(err.Error())
}

fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket)
```

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

## Making a Bucket Public using a Canned ACL
<a name="s3-examples-bucket-acls-make-bucket-public-acl"></a>

As in the previous example, the [PutBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketAcl) function sets the ACLs on a bucket.

The following example gives everyone read-only access to the items in the bucket with the bucket name specified as a command line argument.

Create the file *s3\$1make\$1bucket\$1public.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"

    "fmt"
    "os"
)
```

Create a function to display errors and exit.

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

Get the required input parameter and create the **acl**.

```
if len(os.Args) < 2 {
    exitErrorf("Bucket name required.\nUsage: go run", os.Args[0], "BUCKET")
}

bucket := os.Args[1]
acl := "public-read"
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials` the region from the shared configuration file `~/.aws/config`, and create a new Amazon S3 service client.

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

Create the input for and call [PutBucketAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketAcl). If an error occurs, display a message and quit. Otherwise, display a message indicating success.

```
params := &s3.PutBucketAclInput{
    Bucket: &bucket,
    ACL: &acl,
}

// Set bucket ACL
_, err := svc.PutBucketAcl(params)
if err != nil {
    exitErrorf(err.Error())
}

fmt.Println("Bucket " + bucket + " is now public")
```

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

## Get a Bucket Object ACL
<a name="s3-examples-bucket-acls-get-bucket-object-acl"></a>

The [PutObjectAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObjectAcl) function sets the ACLs on a bucket item.

The following example gets the ACLs for a bucket item with the bucket and item name specified as command line arguments.

Create the file *s3\$1get\$1bucket\$1object\$1acl.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    
    "fmt"
    "os"
)
```

Create a function to display errors and exit.

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

This example requires two input parameters, the names of the bucket and object. If either name is not supplied, call the error function and exit.

```
if len(os.Args) != 3 {
    exitErrorf("Bucket and object names required\nUsage: go run", os.Args[0], "BUCKET OBJECT")
}

bucket := os.Args[1]
key := os.Args[2]
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, the region from the shared configuration file `~/.aws/config`, and create a new Amazon S3 service client.

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

// Create S3 service client
svc := s3.New(sess)
```

Call [GetObjectAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetObjectAcl), passing in the names of the bucket and object. If an error occurs, call `exitErrorf`. If no error occurs, loop through the results and print out the name, type, and permission for the grantees.

```
result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{Bucket: &bucket, Key: &key})
if err != nil {
    exitErrorf(err.Error())
}

fmt.Println("Owner:", *result.Owner.DisplayName)
fmt.Println("")
fmt.Println("Grants")

for _, g := range result.Grants {
    fmt.Println("  Grantee:   ", *g.Grantee.DisplayName)
    fmt.Println("  Type:      ", *g.Grantee.Type)
    fmt.Println("  Permission:", *g.Permission)
    fmt.Println("")
}
```

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

## Set a Bucket Object ACL
<a name="s3-examples-bucket-acls-set-bucket-object-acl"></a>

The [PutObjectAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObjectAcl) function sets the ACLs on a bucket item.

The following example gives a user access by email address to a bucket item, with the bucket and item names and email address specified as command line arguments. The user can also supply a permission argument. However, if it isn’t supplied, the user is given READ access to the bucket.

Create the file *s3\$1put\$1bucket\$1object\$1acl.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    
    "fmt"
    "os"
)
```

Create a function to display errors and exit.

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

Get the three required input parameters. If the optional permission parameter is supplied, make sure it is one of the allowed values. If not, print an error message and quit.

```
if len(os.Args) < 4 {
    exitErrorf("Bucket name, object name, and email address required; permission optional (READ if omitted)\nUsage: go run", os.Args[0], "BUCKET OBJECT EMAIL [PERMISSION]")
}

bucket := os.Args[1]
key := os.Args[2]
address := os.Args[3]

permission := "READ"

if len(os.Args) == 5 {
    permission = os.Args[4]

    if !(permission == "FULL_CONTROL" || permission == "WRITE" || permission == "WRITE_ACP" || permission == "READ" || permission == "READ_ACP") {
        fmt.Println("Illegal permission value. It must be one of:")
        fmt.Println("FULL_CONTROL, WRITE, WRITE_ACP, READ, or READ_ACP")
        os.Exit(1)
    }
}
```

Initialize the session that the SDK uses to load credentials from the shared credentials file `~/.aws/credentials`, and create a new Amazon S3 service client.

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

// Create S3 service client
svc := s3.New(sess)
```

Build the parameter list for the call based on the existing ACLs and the new user information.

```
result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{Bucket: &bucket, Key: &key})
if err != nil {
    exitErrorf(err.Error())
}

owner := *result.Owner.DisplayName
ownerId := *result.Owner.ID

// Existing grants
grants := result.Grants

// Create new grantee to add to grants
userType := "AmazonCustomerByEmail"
var newGrantee = s3.Grantee{EmailAddress: &address, Type: &userType}
var newGrant = s3.Grant{Grantee: &newGrantee, Permission: &permission}

// Add them to the grants
grants = append(grants, &newGrant)

params := &s3.PutObjectAclInput{
    Bucket: &bucket,
    Key:    &key,
    AccessControlPolicy: &s3.AccessControlPolicy{
        Grants: grants,
        Owner: &s3.Owner{
            DisplayName: &owner,
            ID:          &ownerId,
        },
    },
}
```

Call [PutObjectAcl](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObjectAcl), passing in the parameter list. If an error occurs, display a message and quit. Otherwise, display a message indicating success.

```
_, err = svc.PutObjectAcl(params)
if err != nil {
    exitErrorf(err.Error())
}

fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket, "object", key)
```

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

# Encrypting Amazon S3 Bucket Items
<a name="s3-examples-encryption"></a>

Amazon S3 supports encrypting Amazon S3 bucket objects on both the client and the server. To encrypt objects on the client, you perform the encryption yourself, either using keys that you create or keys that AWS Key Management Service (AWS KMS) manages for you.

To encrypt objects on the server, you have more options.
+ You can have Amazon S3 automatically encrypt objects as you upload them to a bucket. Once you configure a bucket with this option, every object that you upload–from that point on–is encrypted.
+ You can encrypt objects yourself before you upload them to a bucket. The disadvantage with this approach is that you can still upload objects that are not encrypted. We don’t show this approach in the documentation.
+ You can have Amazon S3 reject objects that you attempt to upload to a bucket without requesting Amazon S3 encrypt the items.

The following examples describe some of these options.

Learn about encryption in Amazon S3 at [Protecting Data Using Encryption](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingEncryption.html).

**Topics**
+ [Setting Default Server-Side Encryption for an Amazon S3 Bucket](s3-example-default-server-side-encryption.md)
+ [Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects](s3-example-enforce-server-side-encryption.md)
+ [Encrypting an Amazon S3 Bucket Object on the Server Using AWS KMS](s3-example-server-side-encryption-with-kms.md)

# Setting Default Server-Side Encryption for an Amazon S3 Bucket
<a name="s3-example-default-server-side-encryption"></a>

The following example uses the [PutBucketEncryption](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketEncryption) method to enable KMS server-side encryption on any objects added to `amzn-s3-demo-bucket`.

The only exception is if the user configures their request to explicitly use server-side encryption. In that case, the specified encryption takes precedence.

Choose `Copy` to save the code locally.

Create the file *set\$1default\$1encryption.go*.

Import the required packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"

    "fmt"
    "os"
)
```

Get the KMS key from the command line, where `key` is a KMS key ID as created in the [Creating a CMK in AWS Key Management Service](kms-example-create-key.md) example, and set the bucket name.

```
if len(os.Args) != 2 {
    fmt.Println("You must supply a key")
    os.Exit(1)
}

key := os.Args[1]
bucket := "amzn-s3-demo-bucket"
```

Create a session and Amazon S3 client.

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

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

Create the input for and call `PutBucketEncryption`, and display a success message.

```
defEnc := &s3.ServerSideEncryptionByDefault{KMSMasterKeyID: aws.String(key), SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms)}
rule := &s3.ServerSideEncryptionRule{ApplyServerSideEncryptionByDefault: defEnc}
rules := []*s3.ServerSideEncryptionRule{rule}
serverConfig := &s3.ServerSideEncryptionConfiguration{Rules: rules}
input := &s3.PutBucketEncryptionInput{Bucket: aws.String(bucket), ServerSideEncryptionConfiguration: serverConfig}
_, err := svc.PutBucketEncryption(input)
fmt.Println("Bucket " + bucket + " now has KMS encryption by default")
```

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

# Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects
<a name="s3-example-enforce-server-side-encryption"></a>

The following example uses the [PutBucketPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutBucketPolicy) method to require that objects uploaded to an Amazon S3 bucket have Amazon S3 encrypt the object with an AWS KMS key. Attempts to upload an object without specifying that Amazon S3 encrypt the object with an AWS KMS key raise an `Aws::S3::Errors::AccessDenied` exception.

Avoid using this configuration option if you use default server-side encryption as described in [Setting Default Server-Side Encryption for an Amazon S3 Bucket](s3-example-default-server-side-encryption.md) as they could conflict and result in unexpected results.

Choose `Copy` to save the code locally.

Create the file *require\$1server\$1encryption.go*.

Import the required packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"

    "fmt"
    "os"
    "encoding/json"
)
```

Set the name of the bucket, create a session, and create an Amazon S3 client.

```
bucket := "amzn-s3-demo-bucket"
sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))

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

Create an Amazon S3 policy that requires server-side KMS encryption on objects uploaded to the bucket.

```
PolicyDoc := map[string]interface{}{
    "Version": "2012-10-17",		 	 	 
    "Statement": []map[string]interface{}{
        {
            "Sid": "DenyIncorrectEncryptionHeader",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::" + bucket + "/*",
            "Condition": map[string]interface{}{
                "StringNotEquals": map[string]interface{}{
                    "s3:x-amz-server-side-encryption": "aws:kms",
                },
            },
        },
        {
            "Sid": "DenyUnEncryptedObjectUploads",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::" + bucket + "/*",
            "Condition": map[string]interface{}{
                "Null": map[string]interface{}{
                    "s3:x-amz-server-side-encryption": "true",
                },
            },
        },
    },
}
```

Convert the policy into JSON, create the input for and call `PutBucketPolicy`, apply the policy to the bucket, and print a success message.

```
policy, err := json.Marshal(PolicyDoc)
input := &s3.PutBucketPolicyInput{
    Bucket: aws.String(bucket),
    Policy: aws.String(string(policy)),
}
_, err = svc.PutBucketPolicy(input)
fmt.Println("Set policy for " + bucket)
```

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

# Encrypting an Amazon S3 Bucket Object on the Server Using AWS KMS
<a name="s3-example-server-side-encryption-with-kms"></a>

The following example uses the [PutObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObject) method to add the object `myItem` to the bucket `amzn-s3-demo-bucket` with server-side encryption set to AWS KMS.

Note that this differs from [Setting Default Server-Side Encryption for an Amazon S3 Bucket](s3-example-default-server-side-encryption.md), is in that case, the objects are encrypted without you having to explicitly perform the operation.

Choose `Copy` to save the code locally.

Create the file *encrypt\$1object\$1on\$1server.go*.

Add the required packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"

    "fmt"
    "os"
    "strings"
)
```

Get the KMS key from the command line, where `key` is a KMS key ID as created in the [Creating a CMK in AWS Key Management Service](kms-example-create-key.md) example, and set the bucket and object names.

```
if len(os.Args) != 2 {
    fmt.Println("You must supply a key")
    os.Exit(1)
}

key := os.Args[1]
bucket := "amzn-s3-demo-bucket"
object := "myItem"
```

Create a session and Amazon S3 client.

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

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

Create input for and call `put_object`. Notice that the `server_side_encryption` property is set to `aws:kms`, indicating that Amazon S3 encrypts the object using AWS KMS, and display a success message to the user.

```
input := &s3.PutObjectInput{
    Body:                 strings.NewReader(object),
    Bucket:               aws.String(bucket),
    Key:                  aws.String(object),
    ServerSideEncryption: aws.String("aws:kms"),
    SSEKMSKeyId:          aws.String(key),
}

_, err := svc.PutObject(input)
fmt.Println("Added object " + object + " to bucket " + bucket + " with AWS KMS encryption")
```

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

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

Amazon Simple Email Service (Amazon SES) is an email platform that provides an easy, cost-effective way for you to send and receive email using your own email addresses and domains. You can use the following examples to access Amazon SES using the AWS SDK for Go. For more information about Amazon SES, see the [Amazon SES documentation](https://aws.amazon.com/documentation/ses/).

**Topics**
+ [Listing Valid Amazon SES Email Addresses](ses-example-list-emails.md)
+ [Verifying an Email Address in Amazon SES](ses-example-send-verification.md)
+ [Sending a Message to an Email Address in Amazon SES](ses-example-send-email.md)
+ [Deleting an Email Address in Amazon SES](ses-example-delete-address.md)
+ [Getting Amazon SES Statistics](ses-example-get-statistics.md)

# Listing Valid Amazon SES Email Addresses
<a name="ses-example-list-emails"></a>

The following example demonstrates how to use the AWS SDK for Go to list the valid Amazon SES email addresses.

```
package main

import (
    "fmt"
    "os"

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

func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create SES service client
    svc := ses.New(sess)

    result, err := svc.ListIdentities(&ses.ListIdentitiesInput{IdentityType: aws.String("EmailAddress")})

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    for _, email := range result.Identities {
        var e = []*string{email}

        verified, err := svc.GetIdentityVerificationAttributes(&ses.GetIdentityVerificationAttributesInput{Identities: e})

        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }

        for _, va := range verified.VerificationAttributes {
            if *va.VerificationStatus == "Success" {
                fmt.Println(*email)
            }
        }
    }
}
```

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

# Verifying an Email Address in Amazon SES
<a name="ses-example-send-verification"></a>

The following example demonstrates how to use the AWS SDK for Go to verify an Amazon SES email address.

```
package main

import (
    "fmt"
    
    //go get -u github.com/aws/aws-sdk-go
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ses"
    "github.com/aws/aws-sdk-go/aws/awserr"
)

const (
    // Replace sender@example.com with your "From" address. 
    // This address must be verified with Amazon SES.
    Sender = "sender@example.com"
    
    // Replace recipient@example.com with a "To" address. If your account 
    // is still in the sandbox, this address must be verified.
    Recipient = "recipient@example.com"
)

func main() {
    // Create a new session in the us-west-2 region.
    // Replace us-west-2 with the AWS Region you're using for Amazon SES.
    sess, err := session.NewSession(&aws.Config{
        Region:aws.String("us-west-2")},
    )

    // Create an SES session.
    svc := ses.New(sess)
    
    // Attempt to send the email.
    _, err = svc.VerifyEmailAddress(&ses.VerifyEmailAddressInput{EmailAddress: aws.String(Recipient)})
    
    // Display error messages if they occur.
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case ses.ErrCodeMessageRejected:
                fmt.Println(ses.ErrCodeMessageRejected, aerr.Error())
            case ses.ErrCodeMailFromDomainNotVerifiedException:
                fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error())
            case ses.ErrCodeConfigurationSetDoesNotExistException:
                fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            fmt.Println(err.Error())
        }
    
        return
    }
    
    fmt.Println("Verification sent to address: " + Recipient)
}
```

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

# Sending a Message to an Email Address in Amazon SES
<a name="ses-example-send-email"></a>

The following example demonstrates how to use the AWS SDK for Go to send a message to an Amazon SES email address.

```
package main

import (
    "fmt"
    
    //go get -u github.com/aws/aws-sdk-go
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ses"
    "github.com/aws/aws-sdk-go/aws/awserr"
)

const (
    // Replace sender@example.com with your "From" address. 
    // This address must be verified with Amazon SES.
    Sender = "sender@example.com"
    
    // Replace recipient@example.com with a "To" address. If your account 
    // is still in the sandbox, this address must be verified.
    Recipient = "recipient@example.com"

    // Specify a configuration set. To use a configuration
    // set, comment the next line and line 92.
    //ConfigurationSet = "ConfigSet"
    
    // The subject line for the email.
    Subject = "Amazon SES Test (AWS SDK for Go)"
    
    // The HTML body for the email.
    HtmlBody =  "<h1>Amazon SES Test Email (AWS SDK for Go)</h1><p>This email was sent with " +
                "<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the " +
                "<a href='https://aws.amazon.com/sdk-for-go/'>AWS SDK for Go</a>.</p>"
    
    //The email body for recipients with non-HTML email clients.
    TextBody = "This email was sent with Amazon SES using the AWS SDK for Go."
    
    // The character encoding for the email.
    CharSet = "UTF-8"
)

func main() {
    // Create a new session in the us-west-2 region.
    // Replace us-west-2 with the AWS Region you're using for Amazon SES.
    sess, err := session.NewSession(&aws.Config{
        Region:aws.String("us-west-2")},
    )
    
    // Create an SES session.
    svc := ses.New(sess)
    
    // Assemble the email.
    input := &ses.SendEmailInput{
        Destination: &ses.Destination{
            CcAddresses: []*string{
            },
            ToAddresses: []*string{
                aws.String(Recipient),
            },
        },
        Message: &ses.Message{
            Body: &ses.Body{
                Html: &ses.Content{
                    Charset: aws.String(CharSet),
                    Data:    aws.String(HtmlBody),
                },
                Text: &ses.Content{
                    Charset: aws.String(CharSet),
                    Data:    aws.String(TextBody),
                },
            },
            Subject: &ses.Content{
                Charset: aws.String(CharSet),
                Data:    aws.String(Subject),
            },
        },
        Source: aws.String(Sender),
            // Uncomment to use a configuration set
            //ConfigurationSetName: aws.String(ConfigurationSet),
    }

    // Attempt to send the email.
    result, err := svc.SendEmail(input)
    
    // Display error messages if they occur.
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case ses.ErrCodeMessageRejected:
                fmt.Println(ses.ErrCodeMessageRejected, aerr.Error())
            case ses.ErrCodeMailFromDomainNotVerifiedException:
                fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error())
            case ses.ErrCodeConfigurationSetDoesNotExistException:
                fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            fmt.Println(err.Error())
        }
    
        return
    }
    
    fmt.Println("Email Sent to address: " + Recipient)
    fmt.Println(result)
}
```

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

# Deleting an Email Address in Amazon SES
<a name="ses-example-delete-address"></a>

The following example demonstrates how to use the AWS SDK for Go to delete an Amazon SES email address.

```
package main

import (
    "fmt"
    "os"
    
    //go get -u github.com/aws/aws-sdk-go
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ses"
)

const (
    // Replace sender@example.com with your "From" address
    Sender = "sender@example.com"
    
    // Replace recipient@example.com with a "To" address
    Recipient = "recipient@example.com"
)

func main() {
    // Create a new session in the us-west-2 region
    // Replace us-west-2 with the AWS Region you're using for Amazon SES
    sess, err := session.NewSession(&aws.Config{
        Region:aws.String("us-west-2")},
    )

    if err != nil {
        fmt.Println("Got error creating SES session:")
        fmt.Println(err.Error())
        os.Exit(1)
    }
    
    // Create an SES session
    svc := ses.New(sess)

    // Remove email address
    _, delErr := svc.DeleteVerifiedEmailAddress(&ses.DeleteVerifiedEmailAddressInput{EmailAddress: aws.String(Recipient)})
    
    // Display error message if it occurs
    if delErr != nil {
        fmt.Println("Got error attempting to remove email address: " + Recipient)
        fmt.Println(delErr.Error())
      os.Exit(1)
    }

    // Display success message
    fmt.Println("Removed email address: " + Recipient)
}
```

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

# Getting Amazon SES Statistics
<a name="ses-example-get-statistics"></a>

The following example demonstrates how to use the AWS SDK for Go to get statistics about Amazon SES. Use this information to avoid damaging your reputation when emails are bounced or rejected.

```
package main

import (
    //go get -u github.com/aws/aws-sdk-go
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/ses"

    "fmt"
)

func main() {
    // Initialize a session that the SDK uses to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and configuration from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create an SES session.
    svc := ses.New(sess)
    
    // Attempt to send the email.
    result, err := svc.GetSendStatistics(nil)
    
    // Display any error message
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    dps := result.SendDataPoints

    fmt.Println("Got", len(dps), "datapoints")
    fmt.Println("")

    for _, dp := range dps {
        fmt.Println("Timestamp: ", dp.Timestamp)
        fmt.Println("Attempts:  ", aws.Int64Value(dp.DeliveryAttempts))
        fmt.Println("Bounces:   ", aws.Int64Value(dp.Bounces))
        fmt.Println("Complaints:", aws.Int64Value(dp.Complaints))
        fmt.Println("Rejects:   ", aws.Int64Value(dp.Rejects))
        fmt.Println("")
    }
}
```

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

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

Amazon Simple Notification Service (Amazon SNS) is a web service that enables applications, end users, and devices to instantly send and receive notifications from the cloud. You can use the following examples to access Amazon SNS using the AWS SDK for Go. For more information about Amazon SNS, see the [Amazon SNS documentation](https://aws.amazon.com/documentation/sns/).

**Topics**
+ [Listing Your Amazon SNS Topics](sns-example-list-topics.md)
+ [Creating an Amazon SNS Topic](sns-example-create-topic.md)
+ [List Your Amazon SNS Subscriptions](sns-example-list-subscriptions.md)
+ [Subscribe to an Amazon SNS Topic](sns-example-subscribe.md)
+ [Sending a Message to All Amazon SNS Topic Subscribers](sns-example-publish.md)

# Listing Your Amazon SNS Topics
<a name="sns-example-list-topics"></a>

The following example lists the ARNs of your Amazon SNS topics in your default region.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sns"

    "fmt"
    "os"
)

func main() {
    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file. (~/.aws/credentials).
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    svc := sns.New(sess)

    result, err := svc.ListTopics(nil)
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    for _, t := range result.Topics {
        fmt.Println(*t.TopicArn)
    }
}
```

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

# Creating an Amazon SNS Topic
<a name="sns-example-create-topic"></a>

The following example creates a topic with the name from the command line, in your default region, and displays the resulting topic ARN.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sns"

    "fmt"
    "os"
)

func main() {
    if len(os.Args) < 2 {
        fmt.Println("You must supply a topic name")
        fmt.Println("Usage: go run SnsCreateTopic.go TOPIC")
        os.Exit(1)
    }

    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file. (~/.aws/credentials).
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    svc := sns.New(sess)

    result, err := svc.CreateTopic(&sns.CreateTopicInput{
        Name: aws.String(os.Args[1]),
    })
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    fmt.Println(*result.TopicArn)
}
```

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

# List Your Amazon SNS Subscriptions
<a name="sns-example-list-subscriptions"></a>

The following example lists the ARNs for your Amazon SNS topic subscriptions and the associated topic in your default region.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sns"

    "flag"
    "fmt"
    "os"
)

func main() {
    emailPtr := flag.String("e", "", "The email address of the user subscribing to the topic")
    topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes")

    flag.Parse()

    if *emailPtr == "" || *topicPtr == "" {
        fmt.Println("You must supply an email address and topic ARN")
        fmt.Println("Usage: go run SnsSubscribe.go -e EMAIL -t TOPIC-ARN")
        os.Exit(1)
    }

    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file. (~/.aws/credentials).
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    svc := sns.New(sess)

    result, err := svc.Subscribe(&sns.SubscribeInput{
        Endpoint:              emailPtr,
        Protocol:              aws.String("email"),
        ReturnSubscriptionArn: aws.Bool(true), // Return the ARN, even if user has yet to confirm
        TopicArn:              topicPtr,
    })
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    fmt.Println(*result.SubscriptionArn)
}
```

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

# Subscribe to an Amazon SNS Topic
<a name="sns-example-subscribe"></a>

The following example creates a subscription to the topic with the supplied ARN for the user with the supplied email address in your default region, and displays the resulting ARN.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sns"

    "flag"
    "fmt"
    "os"
)

func main() {
    emailPtr := flag.String("e", "", "The email address of the user subscribing to the topic")
    topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes")

    flag.Parse()

    if *emailPtr == "" || *topicPtr == "" {
        fmt.Println("You must supply an email address and topic ARN")
        fmt.Println("Usage: go run SnsSubscribe.go -e EMAIL -t TOPIC-ARN")
        os.Exit(1)
    }

    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file. (~/.aws/credentials).
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    svc := sns.New(sess)

    result, err := svc.Subscribe(&sns.SubscribeInput{
        Endpoint:              emailPtr,
        Protocol:              aws.String("email"),
        ReturnSubscriptionArn: aws.Bool(true), // Return the ARN, even if user has yet to confirm
        TopicArn:              topicPtr,
    })
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    fmt.Println(*result.SubscriptionArn)
}
```

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

# Sending a Message to All Amazon SNS Topic Subscribers
<a name="sns-example-publish"></a>

The following example sends the message supplied on the command line to all subscribers to the Amazon SNS topic with the ARN specified on the command line.

```
package main

import (
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/sns"

    "flag"
    "fmt"
    "os"
)

func main() {
    msgPtr := flag.String("m", "", "The message to send to the subscribed users of the topic")
    topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes")

    flag.Parse()

    if *msgPtr == "" || *topicPtr == "" {
        fmt.Println("You must supply a message and topic ARN")
        fmt.Println("Usage: go run SnsPublish.go -m MESSAGE -t TOPIC-ARN")
        os.Exit(1)
    }

    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file. (~/.aws/credentials).
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    svc := sns.New(sess)

    result, err := svc.Publish(&sns.PublishInput{
        Message:  msgPtr,
        TopicArn: topicPtr,
    })
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    fmt.Println(*result.MessageId)
}
```

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

# 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.