

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

# Amazon 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.