# Aws Sdk Go V1 > [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#common-examples "Open PDF") --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/common-examples.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#common-examples "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [AWS CloudTrail Examples](./using-cloudtrail-with-go-sdk.html) * [Amazon CloudWatch Examples](./using-cloudwatch-with-go-sdk.html) * [AWS CodeBuild Examples](./using-cb-with-go-sdk.html) * [Amazon DynamoDB Examples](./using-dynamodb-with-go-sdk.html) * [Amazon EC2 Examples](./using-ec2-with-go-sdk.html) * [Amazon Glacier Examples](./using-glacier-with-go-sdk.html) * [IAM Examples](./using-iam-with-go-sdk.html) * [AWS KMS Examples](./using-kms-with-go-sdk.html) * [AWS Lambda Examples](./using-lambda-with-go-sdk.html) * [Amazon Polly Examples](./using-polly-with-go-sdk.html) * [Amazon S3 Examples](./using-s3-with-go-sdk.html) * [Amazon SES Examples](./using-ses-with-go-sdk.html) * [Amazon SNS Examples](./using-sns-with-go-sdk.html) * [Amazon SQS Examples](./using-sqs-with-go-sdk.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Handling Errors SDK Request Examples Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/compliance-validation.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#compliance-validation "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # Compliance Validation for this AWS Product or Service To learn whether an AWS service is within the scope of specific compliance programs, see [AWS services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/) and choose the compliance program that you are interested in. For general information, see [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/). You can download third-party audit reports using AWS Artifact. For more information, see [Downloading Reports in AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html). Your compliance responsibility when using AWS services is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. For more information about your compliance responsibility when using AWS services, see [AWS Security Documentation](https://docs.aws.amazon.com/security/). This AWS product or service follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services (AWS) services it supports. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/). ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Identity and Access Management Resilience Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#configuring-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Creating a SessionSpecifying the AWS RegionSpecifying CredentialsConfiguring a ProxyLogging Service CallsCreating a Custom Endpoint 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/). # Configuring the AWS SDK for Go In the AWS SDK for Go, you can configure settings for service clients, such as the log level and maximum number of retries. Most settings are optional. However, for each service client, you must specify an AWS Region and your credentials. The SDK uses these values to send requests to the correct Region and sign requests with the correct credentials. You can specify these values as part of a session or as environment variables. ## Creating a Session Before you can create a service client you must create a session, which is part of the `github.com/aws/aws-sdk-go/aws/session` package. There are a number of ways of configuring a session but the following are the most common. Create a session using the default Region and credentials: import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" ) // ... sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) Create a session in **us-west-2** : import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" ) // ... sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) See [session](https://docs.aws.amazon.com/sdk-for-go/api/aws/session) for additional information. ## Specifying the AWS Region When you specify the Region, you specify where to send requests, such as `us-west-2` or `us-east-2.` For a list of Regions for each service, see [Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html) in the Amazon Web Services General Reference. The SDK does not have a default Region. To specify a Region: * Set the `AWS_REGION` environment variable to the default Region * Set the `AWS_SDK_LOAD_CONFIG` environment variable to **true** to get the Region value from the _config_ file in the `.aws/` folder in your home directory * Set the **NewSessionWithOptions** method argument **SharedConfigState** to **SharedConfigEnable** when you create a session to get the Region value from the _config_ file in the `.aws/` folder in your home directory * Set the Region explicitly when you create a session If you set a Region using all of these techniques, the SDK uses the Region you explicitly specified in the session. The following examples show you how to configure the environment variable. **Linux, OS X, or Unix** $ export AWS_REGION=us-west-2 **Windows** > set AWS_REGION=us-west-2 The following snippet specifies the Region in a session: sess, err := session.NewSession(&aws.Config{Region: aws.String("us-west-2")}) ## Specifying Credentials The AWS SDK for Go requires credentials (an access key and secret access key) to sign requests to AWS. You can specify your credentials in several different locations, depending on your particular use case. For information about obtaining credentials, see [Setting Up](./setting-up.html). When you initialize a new service client without providing any credential arguments, the SDK uses the [default credential provider chain](https://docs.aws.amazon.com/sdk-for-go/api/aws/defaults/#CredChain) to find AWS credentials. The SDK uses the first provider in the chain that returns credentials without an error. The default provider chain looks for credentials in the following order: 1. Environment variables. 2. Shared credentials file. 3. If your application uses an ECS task definition or RunTask API operation, IAM role for tasks. 4. If your application is running on an Amazon EC2 instance, IAM role for Amazon EC2. The SDK detects and uses the built-in providers automatically, without requiring manual configurations. For example, if you use IAM roles for Amazon EC2 instances, your applications automatically use the instance’s credentials. You don’t need to manually configure credentials in your application. As a best practice, AWS recommends that you specify credentials in the following order: 1. Use IAM roles for tasks if your application uses an ECS task definition or RunTask API operation. 2. Use IAM roles for Amazon EC2 (if your application is running on an Amazon EC2 instance). IAM roles provide applications on the instance temporary security credentials to make AWS calls. IAM roles provide an easy way to distribute and manage credentials on multiple Amazon EC2 instances. 3. Use a shared credentials file. This credentials file is the same one used by other SDKs and the AWS CLI. If you’re already using a shared credentials file, you can also use it for this purpose. 4. Use environment variables. Setting environment variables is useful if you’re doing development work on a machine other than an Amazon EC2 instance. ### IAM Roles for Tasks If your application uses an Amazon ECS task definition or `RunTask` operation, use [IAM Roles for Tasks](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html) to specify an IAM role that can be used by the containers in a task. ### IAM Roles for Amazon EC2 Instances If you are running your application on an Amazon EC2 instance, use the instance’s [IAM role](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) to get temporary security credentials to make calls to AWS. If you have configured your instance to use IAM roles, the SDK uses these credentials for your application automatically. You don’t need to manually specify these credentials. ### Shared Credentials File A credential file is a plaintext file that contains your access keys. The file must be on the same machine on which you’re running your application. The file must be named `credentials` and located in the `.aws/` folder in your home directory. The home directory can vary by operating system. In Windows, you can refer to your home directory by using the environment variable `%UserProfile%`. In Unix-like systems, you can use the environment variable `$HOME` or `~` (tilde). If you already use this file for other SDKs and tools (like the AWS CLI), you don’t need to change anything to use the files in this SDK. If you use different credentials for different tools or applications, you can use _profiles_ to configure multiple access keys in the same configuration file. #### Creating the Credentials File If you don’t have a shared credentials file (`.aws/credentials`), you can use any text editor to create one in your home directory. Add the following content to your credentials file, replacing `` and `` with your credentials. [default] aws_access_key_id = aws_secret_access_key = The `[default]` heading defines credentials for the default profile, which the SDK will use unless you configure it to use another profile. You can also use temporary security credentials by adding the session tokens to your profile, as shown in the following example: [temp] aws_access_key_id = aws_secret_access_key = aws_session_token = #### Specifying Profiles You can include multiple access keys in the same configuration file by associating each set of access keys with a profile. For example, in your credentials file, you can declare multiple profiles, as follows. [default] aws_access_key_id = aws_secret_access_key = [test-account] aws_access_key_id = aws_secret_access_key = [prod-account] ; work profile aws_access_key_id = aws_secret_access_key = By default, the SDK checks the `AWS_PROFILE` environment variable to determine which profile to use. If no `AWS_PROFILE` variable is set, the SDK uses the default profile. If you have an application named `myapp` that uses the SDK, you can run it with the test credentials by setting the variable to `test-account myapp`, as shown in the following command. $ AWS_PROFILE=test-account myapp You can also use the SDK to select a profile by specifying `os.Setenv("AWS_PROFILE", test-account)` before constructing any service clients or by manually setting the credential provider, as shown in the following example. sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewSharedCredentials("", "test-account"), }) In addition, checking if your credentials have been found is fairly easy. _, err := sess.Config.Credentials.Get() If `ChainProvider` is being used, set `CredentialsChainVerboseErrors` to `true` in the session config. ###### Note If you specify credentials in environment variables, the SDK will always use those credentials, no matter which profile you specify. ### Environment Variables By default, the SDK detects AWS credentials set in your environment and uses them to sign requests to AWS. That way you don’t need to manage credentials in your applications. The SDK looks for credentials in the following environment variables: * `AWS_ACCESS_KEY_ID` * `AWS_SECRET_ACCESS_KEY` * `AWS_SESSION_TOKEN` (optional) The following examples show how you configure the environment variables. **Linux, OS X, or Unix** $ export AWS_ACCESS_KEY_ID=YOUR_AKID $ export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY $ export AWS_SESSION_TOKEN=TOKEN **Windows** > set AWS_ACCESS_KEY_ID=YOUR_AKID > set AWS_SECRET_ACCESS_KEY=YOUR_SECRET_KEY > set AWS_SESSION_TOKEN=TOKEN ### Hard-Coded Credentials in an Application (Not Recommended) ###### Warning Do not embed credentials inside an application. Use this method only for testing purposes. You can hard-code credentials in your application by passing the access keys to a configuration instance, as shown in the following snippet. sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials("AKID", "SECRET_KEY", "TOKEN"), }) ### Other Credentials Providers The SDK provides other methods for retrieving credentials in the `aws/credentials` package. For example, you can retrieve temporary security credentials from AWS Security Token Service or credentials from encrypted storage. For more information, see [Credentials](https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials/). ## Configuring a Proxy If you cannot directly connect to the internet, you can use Go-supported environment variables (`HTTP_PROXY`) or create a custom HTTP client to configure your proxy. Use the [Config.HTTPClient](https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config.WithHTTPClient) struct to specify a custom HTTP client. For more information about how to create an HTTP client to use a proxy, see the [Transport](https://golang.org/pkg/net/http/#Transport) struct in the Go `http` package. ## Logging Service Calls You can enable logging in a client by setting the `LogLevel` in a configuration instance, as shown in the following snippet, which sets the log level to `LogDebugWithHTTPBody` for a new DynamoDB client. svc := dynamodb.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody)) See [LogLevelType](https://docs.aws.amazon.com/sdk-for-go/api/aws/#LogLevelType) for the different log level values. ## Creating a Custom Endpoint In most cases you use the endpoint that is pre-configured for a service. However, you can specify a custom endpoint, such as for pre-release versions of the service, as shown in the following snippet, which sets the `Endpoint` to `https://test.us-west-2.amazonaws.com` for a new DynamoDB client. svc := dynamodb.New(sess, &aws.Config{Endpoint: aws.String("https://test.us-west-2.amazonaws.com")}) See [aws.Config](https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config) for details. ###### Topics ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Getting Started Custom HTTP Client Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/custom-http.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#custom-http "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Dialer.KeepAliveDialer.TimeoutTransport.ExpectContinueTimeoutTransport.IdleConnTimeoutTransport.MaxIdleConnsTransport.MaxIdleConnsPerHostTransport.ResponseHeaderTimeoutTransport.TLSHandshakeTimeoutCreate Import StatementCreating a Timeout StructCreating a Function to Create a Custom HTTP ClientUsing a Custom HTTP Client 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/). # Creating a Custom HTTP Client The AWS SDK for Go uses a default HTTP client with default configuration values. Although you can change some of these configuration values, the default HTTP client and transport are not sufficiently configurable for customers using the AWS SDK for Go in an environment with high throughput and low latency requirements. This section describes how to create a custom HTTP client, and use that client to create AWS SDK for Go calls. To assist you in creating a custom HTTP client, this section describes how to create a structure to encapsulate the custom settings, create a function to create a custom HTTP client based on those settings, and use that custom HTTP client to call an AWS SDK for Go service client. Let’s define what we want to customize. ## Dialer.KeepAlive This setting represents the keep-alive period for an active network connection. Set to a negative value to disable keep-alives. Set to **0** to enable keep-alives if supported by the protocol and operating system. Network protocols or operating systems that do not support keep-alives ignore this field. By default, TCP enables keep alive. See [https://golang.org/pkg/net/#Dialer.KeepAlive](https://golang.org/pkg/net/#Dialer.KeepAlive) We’ll call this `ConnKeepAlive` as **time.Duration**. ## Dialer.Timeout This setting represents the maximum amount of time a dial to wait for a connection to be created. Default is 30 seconds. See [https://golang.org/pkg/net/#Dialer.Timeout](https://golang.org/pkg/net/#Dialer.Timeout) We’ll call this `Connect` as **time.Duration**. ## Transport.ExpectContinueTimeout This setting represents the maximum amount of time to wait for a server’s first response headers after fully writing the request headers, if the request has an “Expect: 100-continue” header. This time does not include the time to send the request header. The HTTP client sends its payload after this timeout is exhausted. Default 1 second. Set to **0** for no timeout and send request payload without waiting. One use case is when you run into issues with proxies or third party services that take a session similar to the use of Amazon S3 in the function shown later. See [https://golang.org/pkg/net/http/#Transport.ExpectContinueTimeout](https://golang.org/pkg/net/http/#Transport.ExpectContinueTimeout) We’ll call this `ExpectContinue` as **time.Duration**. ## Transport.IdleConnTimeout This setting represents the maximum amount of time to keep an idle network connection alive between HTTP requests. Set to **0** for no limit. See [https://golang.org/pkg/net/http/#Transport.IdleConnTimeout](https://golang.org/pkg/net/http/#Transport.IdleConnTimeout) We’ll call this `IdleConn` as **time.Duration**. ## Transport.MaxIdleConns This setting represents the maximum number of idle (keep-alive) connections across all hosts. One use case for increasing this value is when you are seeing many connections in a short period from the same clients **0** means no limit. See [https://golang.org/pkg/net/http/#Transport.MaxIdleConns](https://golang.org/pkg/net/http/#Transport.MaxIdleConns) We’ll call this `MaxAllIdleConns` as **int**. ## Transport.MaxIdleConnsPerHost This setting represents the maximum number of idle (keep-alive) connections to keep per-host. One use case for increasing this value is when you are seeing many connections in a short period from the same clients Default is two idle connections per host. Set to **0** to use DefaultMaxIdleConnsPerHost (2). See [https://golang.org/pkg/net/http/#Transport.MaxIdleConnsPerHost](https://golang.org/pkg/net/http/#Transport.MaxIdleConnsPerHost) We’ll call this `MaxHostIdleConns` as **int**. ## Transport.ResponseHeaderTimeout This setting represents the maximum amount of time to wait for a client to read the response header. If the client isn’t able to read the response’s header within this duration, the request fails with a timeout error. Be careful setting this value when using long-running Lambda functions, as the operation does not return any response headers until the Lambda function has finished or timed out. However, you can still use this option with the **InvokeAsync** API operation. Default is no timeout; wait forever. See [https://golang.org/pkg/net/http/#Transport.ResponseHeaderTimeout](https://golang.org/pkg/net/http/#Transport.ResponseHeaderTimeout) We’ll call this `ResponseHeader` as **time.Duration**. ## Transport.TLSHandshakeTimeout This setting represents the maximum amount of time waiting for a TLS handshake to be completed. Default is 10 seconds. Zero means no timeout. See [https://golang.org/pkg/net/http/#Transport.TLSHandshakeTimeout](https://golang.org/pkg/net/http/#Transport.TLSHandshakeTimeout) We’ll call this `TLSHandshake` as **time.Duration**. ## Create Import Statement The complete example imports the following Go packages. import ( "bytes" "context" "flag" "fmt" "io" "net" "net/http" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "golang.org/x/net/http2" ) ## Creating a Timeout Struct Let’s create a struct to hold the timeout values we want to be able to set on our HTTP client. type HTTPClientSettings struct { Connect time.Duration ConnKeepAlive time.Duration ExpectContinue time.Duration IdleConn time.Duration MaxAllIdleConns int MaxHostIdleConns int ResponseHeader time.Duration TLSHandshake time.Duration } ## Creating a Function to Create a Custom HTTP Client Next let’s create a function that takes a **ClientTimeout** struct and creates a custom HTTP client based on those timeout values. func NewHTTPClientWithSettings(httpSettings HTTPClientSettings) (*http.Client, error) { var client http.Client tr := &http.Transport{ ResponseHeaderTimeout: httpSettings.ResponseHeader, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ KeepAlive: httpSettings.ConnKeepAlive, DualStack: true, Timeout: httpSettings.Connect, }).DialContext, MaxIdleConns: httpSettings.MaxAllIdleConns, IdleConnTimeout: httpSettings.IdleConn, TLSHandshakeTimeout: httpSettings.TLSHandshake, MaxIdleConnsPerHost: httpSettings.MaxHostIdleConns, ExpectContinueTimeout: httpSettings.ExpectContinue, } // So client makes HTTP/2 requests err := http2.ConfigureTransport(tr) if err != nil { return &client, err } return &http.Client{ Transport: tr, }, nil } ## Using a Custom HTTP Client Let’s create a custom HTTP client and use it to create an Amazon S3 client. The following example creates an **http.Client** that is configured to have: * a five second TCP connection timeout * a five second TLS handshake timeout * a five second wait for the HTTP response headers httpClient, err := NewHTTPClientWithSettings(HTTPClientSettings{ Connect: 5 * time.Second, ExpectContinue: 1 * time.Second, IdleConn: 90 * time.Second, ConnKeepAlive: 30 * time.Second, MaxAllIdleConns: 100, MaxHostIdleConns: 10, ResponseHeader: 5 * time.Second, TLSHandshake: 5 * time.Second, }) if err != nil { fmt.Println("Got an error creating custom HTTP client:") fmt.Println(err) return } sess := session.Must(session.NewSession(&aws.Config{ HTTPClient: httpClient, })) svc := s3.New(sess) All of these settings give the client approximately 15 seconds create a connection, do a TLS handshake, and receive the response headers from the service. The time that the client takes to read the response body is not covered by these timeouts. To specify a total timeout for the request to include reading the response body, use the AWS SDK for Go client’s **WithContext** API operation methods, such as the Amazon S3 operation [PutObjectWithContext](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.PutObjectWithContext) with a **context.Withtimeout**. The following example uses a timeout context to limit the total time an API request can be active to a maximum of 20 seconds. The SDK must be able to read the full HTTP response body (Object body) within the timeout or the SDK returns a timeout error. For API operations that return an **io.ReadCloser** in their response type, the Context’s timeout includes reading the content from the **io.ReadCloser**. ctx, cancelFn := context.WithTimeout(context.TODO(), 20*time.Second) defer cancelFn() resp, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ Bucket: bucket, Key: object, }) if err != nil { return body, err } return resp.Body, nil See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/s3/CustomClient/CustomHttpClient.go) on GitHub. ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Configuring the SDK Using Sessions Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/data-protection.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#data-protection "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # Data Protection in this AWS Product or Service The AWS [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) applies to data protection in this AWS product or service. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. You are also responsible for the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the [Data Privacy FAQ](https://aws.amazon.com/compliance/data-privacy-faq/). For information about data protection in Europe, see the [AWS Shared Responsibility Model and GDPR](https://aws.amazon.com/blogs/security/the-aws-shared-responsibility-model-and-gdpr/) blog post on the _AWS Security Blog_. For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: * Use multi-factor authentication (MFA) with each account. * Use SSL/TLS to communicate with AWS resources. We require TLS 1.2 and recommend TLS 1.3. * Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see [Working with CloudTrail trails](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-trails.html) in the _AWS CloudTrail User Guide_. * Use AWS encryption solutions, along with all default security controls within AWS services. * Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3. * If you require FIPS 140-3 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see [Federal Information Processing Standard (FIPS) 140-3](https://aws.amazon.com/compliance/fips/). We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a **Name** field. This includes when you work with this AWS product or service or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server. ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Security Identity and Access Management Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/disaster-recovery-resiliency.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#disaster-recovery-resiliency "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # Resilience for this AWS Product or Service The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between zones without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. For more information about AWS Regions and Availability Zones, see [AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/). This AWS product or service follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services (AWS) services it supports. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/). ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Compliance Validation Infrastructure Security Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/document-history.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#document-history "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # Document History This topic describes important changes to the AWS SDK for Go Developer Guide over the course of its history. To view the list of changes to the AWS SDK for Go and its documentation, see the [CHANGELOG.md](https://github.com/aws/aws-sdk-go/blob/main/CHANGELOG.md) file in the `aws/aws-sdk-go` repository in GitHub. **Last documentation update:** Dec 29, 2021 **Feb 7, 2022** Removed SDK Metrics material. This feature was deprecated on December 31, 2021. **Jul 10, 2017** Added the Document History topic. **June 14, 2017** Updated error handling example code. **April 14, 2017** Added S3 policy example. **April 11, 2017** Added S3 bucket ACL examples. **April 7, 2017** Added samples of getting/setting bucket and bucket object ACLs. **March 28, 2017** Updated basic Amazon S3 bucket examples. **February 27, 2017** Added an example of AssumeRoleTokenProvider. **November 2, 2016** Added SDK setters examples. **October 23, 2016** Changed deprecated session.New to session.NewSession. **September 29, 2016** Added a new topic for handling service errors from GitHub repository. **September 28, 2016** Added an example of Go extending SDK for context.Context. **August 31, 2016** Initial release of the AWS SDK for Go Developer Guide. ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) S3 Encryption Client Migration Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/handling-errors.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#handling-errors "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Handling Specific Service Error CodesAdditional Error Information 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/). # Handling Errors in the AWS SDK for Go The AWS SDK for Go returns errors that satisfy the Go `error` interface type and the [Error](https://docs.aws.amazon.com/sdk-for-go/api/aws/awserr/#Error) interface in the `aws/awserr` package. You can use the `Error()` method to get a formatted string of the SDK error message without any special handling. if err != nil { if awsErr, ok := err.(awserr.Error); ok { // process SDK error } } Errors returned by the SDK are backed by a concrete type that will satisfy the `awserr.Error` interface. The interface has the following methods, which provide classification and information about the error. * `Code` returns the classification code by which related errors are grouped. * `Message` returns a description of the error. * `OrigErr` returns the original error of type `error` that is wrapped by the `awserr.Error` interface, such as a standard library error or a service error. ## Handling Specific Service Error Codes The following example demonstrates how to handle error codes that you encounter while using the AWS SDK for Go. The example assumes you have already set up and configured the SDK (that is, all required packages are imported and your credentials and region are set). For more information, see [Getting Started with the AWS SDK for Go](./setting-up.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). This example highlights how you can use the `awserr.Error` type to perform logic based on specific error codes returned by service API operations. In this example the _S3_ _GetObject_ API operation is used to request the contents of an object in S3. The example handles the _NoSuchBucket_ and _NoSuchKey_ error codes, printing custom messages to stderr. If any other error is received, a generic message is printed. svc := s3.New(sess) resp, err := svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String(os.Args[1]), Key: aws.String(os.Args[2]), }) if err != nil { // Casting to the awserr.Error type will allow you to inspect the error // code returned by the service in code. The error code can be used // to switch on context specific functionality. In this case a context // specific error message is printed to the user based on the bucket // and key existing. // // For information on other S3 API error codes see: // http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchBucket: exitErrorf("bucket %s does not exist", os.Args[1]) case s3.ErrCodeNoSuchKey: exitErrorf("object with key %s does not exist in bucket %s", os.Args[2], os.Args[1]) } } See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/extending_sdk/handleServiceErrorCodes.go) on GitHub. ## Additional Error Information In addition to the `awserr.Error` interface, you might be able to use other interfaces to get more information about an error. ### Specific Error Interfaces Other packages might provide their own error interfaces. For example, the [service/s3/s3manager](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager) package provides a [MultiUploadFailure](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#MultiUploadFailure) interface to retrieve the upload ID. This is helpful when you must manually clean up a failed multi-part upload. output, err := s3manager.Upload(svc, input, opts) if err != nil { if multierr, ok := err.(MultiUploadFailure); ok { // Process error and its associated uploadID fmt.Println("Error:", multierr.Code(), multierr.Message(), multierr.UploadID()) } else { // Process error generically fmt.Println("Error:", err.Error()) } } For more information, see the [s3Manager.MultiUploadFailure](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#MultiUploadFailure) interface in the AWS SDK for Go API Reference. ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Using AWS Services Code Examples Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/infrastructure-security.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#infrastructure-security "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # Infrastructure Security for this AWS Product or Service This AWS product or service uses managed services, and therefore is protected by the AWS global network security. For information about AWS security services and how AWS protects infrastructure, see [AWS Cloud Security](https://aws.amazon.com/security/). To design your AWS environment using the best practices for infrastructure security, see [Infrastructure Protection](https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/infrastructure-protection.html) in _Security Pillar AWS Well‐Architected Framework_. You use AWS published API calls to access this AWS Product or Service through the network. Clients must support the following: * Transport Layer Security (TLS). We require TLS 1.2 and recommend TLS 1.3. * Cipher suites with perfect forward secrecy (PFS) such as DHE (Ephemeral Diffie-Hellman) or ECDHE (Elliptic Curve Ephemeral Diffie-Hellman). Most modern systems such as Java 7 and later support these modes. Additionally, requests must be signed by using an access key ID and a secret access key that is associated with an IAM principal. Or you can use the [AWS Security Token Service](https://docs.aws.amazon.com/STS/latest/APIReference/Welcome.html) (AWS STS) to generate temporary security credentials to sign requests. This AWS product or service follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services (AWS) services it supports. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/). ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Resilience Enforcing a minimum TLS version Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/making-requests.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#making-requests "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Constructing a ServiceTagging Service ResourcesGetting the HTTP Request and Response with Each Service CallService Operation CallsConcurrently Using Service ClientsUsing Pagination MethodsUsing Waiters 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/). # Using the AWS SDK for Go with AWS Services To make calls to an AWS service, you must first construct a service client instance with a session. A service client provides low-level access to every API action for that service. For example, you create an Amazon S3 service client to make calls to Amazon S3. When you call service operations, you pass in input parameters as a struct. A successful call usually results in an output struct that you can use. For example, after you successfully call an Amazon S3 create bucket action, the action returns an output struct with the bucket’s location. For the list of service clients, including their methods and parameters, see the [AWS SDK for Go API Reference](https://docs.aws.amazon.com/sdk-for-go/api/). ## Constructing a Service To construct a service client instance, use the [NewSession()](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/#NewSession) function. The following example creates an Amazon S3 service client. sess, err := session.NewSession() if err != nil { fmt.Println("Error creating session ", err) return } svc := s3.New(sess) After you have a service client instance, you can use it to call service operations. For more information about configurations, see [Configuring the AWS SDK for Go](./configuring-sdk.html). When you create a service client, you can pass in custom configurations so that you don’t need to create a session for each configuration. The SDK merges the two configurations, overriding session values with your custom configuration. For example, in the following snippet, the Amazon S3 client uses the `mySession` session but overrides the `Region` field with a custom value (`us-west-2`): svc := s3.New(mySession, aws.NewConfig().WithRegion("us-west-2")) ## Tagging Service Resources You can tag service resources, such as Amazon S3 buckets, so that you can determine the costs of your service resources at whatever level of granularity you require. The following example shows how to tag the Amazon S3 bucket `amzn-s3-demo-bucket` with `Cost Center` tag with the value `123456` and `Stack` tag with the value `MyTestStack`. 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" "fmt" ) // Tag S3 bucket amzn-s3-demo-bucket with cost center tag "123456" and stack tag "MyTestStack". // // See: // http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html func main() { // Pre-defined values bucket := "amzn-s3-demo-bucket" tagName1 := "Cost Center" tagValue1 := "123456" tagName2 := "Stack" tagValue2 := "MyTestStack" // 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")}, ) if err != nil { fmt.Println(err.Error()) return } // Create S3 service client svc := s3.New(sess) // Create input for PutBucket method putInput := &s3.PutBucketTaggingInput{ Bucket: aws.String(bucket), Tagging: &s3.Tagging{ TagSet: []*s3.Tag{ { Key: aws.String(tagName1), Value: aws.String(tagValue1), }, { Key: aws.String(tagName2), Value: aws.String(tagValue2), }, }, }, } _, err = svc.PutBucketTagging(putInput) if err != nil { fmt.Println(err.Error()) return } // Now show the tags // Create input for GetBucket method getInput := &s3.GetBucketTaggingInput{ Bucket: aws.String(bucket), } result, err := svc.GetBucketTagging(getInput) if err != nil { fmt.Println(err.Error()) return } numTags := len(result.TagSet) if numTags > 0 { fmt.Println("Found", numTags, "Tag(s):") fmt.Println("") for _, t := range result.TagSet { fmt.Println(" Key: ", *t.Key) fmt.Println(" Value:", *t.Value) fmt.Println("") } } else { fmt.Println("Did not find any tags") } } Note that if a tag of the same name already exists, its value is overwritten by the new value. ## Getting the HTTP Request and Response with Each Service Call You can direct the AWS SDK for Go to display the HTTP request and response it sends and receives for each call by including a configuration option when constructing the service client. The following example uses the DynamoDB **ListTables** operation to illustrate how to add a custom header to a service call. package main import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "fmt" "os" ) func main() { // Initialize a session in us-west-2 that the SDK will use to load credentials // from the shared config file. (~/.aws/credentials). sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) if err != nil { fmt.Println("Error getting session:") fmt.Println(err) os.Exit(1) } // Create DynamoDB client // and expose HTTP requests/responses svc := dynamodb.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody)) // Add "CustomHeader" header with value of 10 svc.Handlers.Send.PushFront(func(r *request.Request) { r.HTTPRequest.Header.Set("CustomHeader", fmt.Sprintf("%d", 10)) }) // Call ListTables just to see HTTP request/response // The request should have the CustomHeader set to 10 _, _ = svc.ListTables(&dynamodb.ListTablesInput{}) } If you run this program, the output should be similar to the following, where **ACCESS-KEY** is the access key of the user and **TABLE-1** , through **TABLE-N** are the names of the tables. 2017/10/25 11:10:57 DEBUG: Request dynamodb/ListTables Details: ---[ REQUEST POST-SIGN ]----------------------------- POST / HTTP/1.1 Host: dynamodb.us-west-2.amazonaws.com User-Agent: aws-sdk-go/1.10.34 (go1.8; windows; amd64) Content-Length: 2 Accept-Encoding: identity Authorization: AWS4-HMAC-SHA256 Credential=ACCESS-KEY/20171025/us-west-2/dynamodb/aws4_request, SignedHeaders=accept-encoding;content-length;content-type;host;x-amz-date;x-amz-target, Signature=9c92efe5d6c597cf29e4f7cc74de6dc2e39f8010a0d4957a397c59ef9cde21f2 Content-Type: application/x-amz-json-1.0 CustomHeader: 10 X-Amz-Date: 20171025T181057Z X-Amz-Target: DynamoDB_20120810.ListTables {} ----------------------------------------------------- 2017/10/25 11:10:58 DEBUG: Response dynamodb/ListTables Details: ---[ RESPONSE ]-------------------------------------- HTTP/1.1 200 OK Content-Length: 177 Connection: keep-alive Content-Type: application/x-amz-json-1.0 Date: Wed, 25 Oct 2017 18:10:58 GMT Server: Server X-Amz-Crc32: 3023160996 X-Amzn-Requestid: M5B4BM4UU569MVBSDG5O2O9ITJVV4KQNSO5AEMVJF66Q9ASUAAJG ----------------------------------------------------- 2017/10/25 11:10:58 {"TableNames":["TABLE-1","...","TABLE-N"]} ## Service Operation Calls You can call a service operation directly or with its request form. When you call a service operation, the SDK synchronously validates the input, builds the request, signs it with your credentials, sends it to AWS, and then gets a response or an error. In most cases, you can call service operations directly. ### Calling Operations Calling the operation will sync as the request is built, signed, sent, and the response is received. If an error occurs during the operation, it will be returned. The output or resulting structure won’t be valid. For example, to call the Amazon S3 GET Object API, use the Amazon S3 service client instance and call its [GetObject](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#S3.GetObject) method: result, err := s3Svc.GetObject(&s3.GetObjectInput{...}) // result is a *s3.GetObjectOutput struct pointer // err is a error which can be cast to awserr.Error. #### Passing Parameters to a Service Operation When calling an operation on a service, you pass in input parameters as option values, similar to passing in a configuration. For example, to retrieve an object, you must specify a bucket and the object’s key by passing in the following parameters to the `GetObject` method: svc := s3.New(session.New()) svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String("amzn-s3-demo-bucket"), Key: aws.String("keyName"), }) Each service operation has an associated input struct and, usually, an output struct. The structs follow the naming pattern _OperationName_ `Input` and _OperationName_ `Output`. For more information about the parameters of each method, see the service client documentation in the [AWS SDK for Go API Reference](https://docs.aws.amazon.com/sdk-for-go/api/). ### Calling Operations with the Request Form Calling the request form of a service operation, which follows the naming pattern _OperationName_ `Request`, provides a simple way to control when a request is built, signed, and sent. Calling the request form immediately returns a request object. The request object output is a struct pointer that is not valid until the request is sent and returned successfully. Calling the request form can be useful when you want to construct a number of pre-signed requests, such as pre-signed Amazon S3 URLs. You can also use the request form to modify how the SDK sends a request. The following example calls the request form of the `GetObject` method. The [Send](https://docs.aws.amazon.com/sdk-for-go/api/aws/request/#Request.Send) method signs the request before sending it. req, result := s3Svc.GetObjectRequest(&s3.GetObjectInput{...}) // result is a *s3.GetObjectOutput struct pointer, not populated until req.Send() returns // req is a *aws.Request struct pointer. Used to Send request. if err := req.Send(); err != nil { // process error return } // Process result ### Handling Operation Response Body Some API operations return a response struct that contain a `Body` field that is an `io.ReadCloser`. If you’re making requests with these operations, always be sure to call `Close` on the field. resp, err := s3svc.GetObject(&s3.GetObjectInput{...}) if err != nil { // handle error return } // Make sure to always close the response Body when finished defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) if err := decoder.Decode(&myStruct); err != nil { // handle error return } ## Concurrently Using Service Clients You can create goroutines that concurrently use the same service client to send multiple requests. You can use a service client with as many goroutines as you want. However, you cannot concurrently modify the service client’s configuration and request handlers. If you do, the service client operations might encounter race conditions. Define service client settings before you concurrently use it. In the following example, an Amazon S3 service client is used in multiple goroutines. The example concurrently outputs all objects in `amzn-s3-demo-bucket1`, `amzn-s3-demo-bucket2`, and `amzn-s3-demo-bucket3`, which are all in the same region. To make sure all objects from the same bucket are printed together, the example uses a channel. sess, err := session.NewSession() if err != nil { fmt.Println("Error creating session ", err) } var wg sync.WaitGroup keysCh := make(chan string, 10) svc := s3.New(sess) buckets := []string{"amzn-s3-demo-bucket1", "amzn-s3-demo-bucket2", "amzn-s3-demo-bucket3"} for _, bucket := range buckets { params := &s3.ListObjectsInput{ Bucket: aws.String(bucket), MaxKeys: aws.Int64(100), } wg.Add(1) go func(param *s3.ListObjectsInput) { defer wg.Done() err = svc.ListObjectsPages(params, func(page *s3.ListObjectsOutput, last bool) bool { // Add the objects to the channel for each page for _, object := range page.Contents { keysCh <- fmt.Sprintf("%s:%s", *params.Bucket, *object.Key) } return true }, ) if err != nil { fmt.Println("Error listing", *params.Bucket, "objects:", err) } }(params) } go func() { wg.Wait() close(keysCh) }() for key := range keysCh { // Print out each object key as its discovered fmt.Println(key) } ## Using Pagination Methods Typically, when you retrieve a list of items, you might need to check the output for a token or marker to confirm whether AWS returned all results from your request. If present, you use the token or marker to request the next set of results. Instead of managing these tokens or markers, you can use pagination methods provided by the SDK. Pagination methods iterate over a list operation until the method retrieves the last page of results or until the callback function returns `false`. The names of these methods use the following pattern: _OperationName_ `Pages`. For example, the pagination method for the Amazon S3 list objects operation (`ListObjects`) is `ListObjectPages`. The following example uses the `ListObjectPages` pagination method to list up to three pages of object keys from the `ListObject` operation. Each page consists of up to 10 keys, which is defined by the `MaxKeys` field. svc, err := s3.NewSession(sess) if err != nil { fmt.Println("Error creating session ", err) } inputparams := &s3.ListObjectsInput{ Bucket: aws.String("amzn-s3-demo-bucket"), MaxKeys: aws.Int64(10), } pageNum := 0 svc.ListObjectsPages(inputparams, func(page *s3.ListObjectsOutput, lastPage bool) bool { pageNum++ for _, value := range page.Contents { fmt.Println(*value.Key) } return pageNum < 3 }) ## Using Waiters The SDK provides waiters that continuously check for completion of a job. For example, when you send a request to create an Amazon S3 bucket, you can use a waiter to check when the bucket has been successfully created. That way, subsequent operations on the bucket are done only after the bucket has been created. The following example uses a waiter that waits until specific instances have stopped. sess, err := session.NewSession(aws.NewConfig().WithRegion("us-west-2")) if err != nil { fmt.Println("Error creating session ", err) } // Create an EC2 client ec2client := ec2.New(sess) // Specify two instances to stop instanceIDsToStop := aws.StringSlice([]string{"i-12345678", "i-23456789"}) // Send request to stop instances _, err = ec2client.StopInstances(&ec2.StopInstancesInput{ InstanceIds: instanceIDsToStop, }) if err != nil { panic(err) } // Use a waiter function to wait until the instances are stopped describeInstancesInput := &ec2.DescribeInstancesInput{ InstanceIds: instanceIDsToStop, } if err := ec2client.WaitUntilInstanceStopped(describeInstancesInput); err != nil { panic(err) } fmt.Println("Instances are stopped.") ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Using Sessions Handling Errors Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/s3-encryption-migration.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#s3-encryption-migration "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Migration OverviewUpdate Existing Clients to Read New FormatsMigrate Encryption and Decryption Clients to V2 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 Encryption Client Migration This topic shows how to migrate your applications from Version 1 (V1) of the Amazon Simple Storage Service (Amazon S3) encryption client to Version 2 (V2) and ensure application availability throughout the migration process. ## Migration Overview This migration happens in two phases: 1\. **Update existing clients to read new formats.** First, deploy an updated version of the AWS SDK for Go to your application. This allows existing V1 encryption clients to decrypt objects written by the new V2 clients. If your application uses multiple AWS SDKs, you must upgrade each SDK separately. 2\. **Migrate encryption and decryption clients to V2.** Once all of your V1 encryption clients can read new formats, you can migrate your existing encryption and decryption clients to their respective V2 versions. ## Update Existing Clients to Read New Formats The V2 encryption client uses encryption algorithms that older versions of the client do not support. The first step in the migration is to update your V1 decryption clients to SDK version v1.34.0 or later. After completing this step, your application’s V1 clients will be able to decrypt objects encrypted by V2 encryption clients. ### Update Applications That Use Go Modules If your applications use the Go module dependency system introduced in Go 1.11, you must take the following steps to update your application to the latest release of the AWS SDK for Go. First, update your SDK module dependency. $ go get github.com/aws/aws-sdk-go@latest Next, validate your dependency has correctly updated to the required minimum version. $ go list -m github.com/aws/aws-sdk-go github.com/aws/aws-sdk-go v1.34.0 After you upgrade and validate your dependencies, deploy the application to your fleet. Once the rollout is complete, you can migrate your V1 encryption and decryption clients to V2. ### Updating Applications That Use GOPATH If your application uses `GOPATH` to manage its dependencies, you must take the following steps to update and verify that your application is using the minimum SDK release or later. First, update your SDK `GOPATH` source code. $ go get -u github.com/aws/aws-sdk-go Next, ensure the SDK source path to the release (v1.34.0) or later ([https://github.com/aws/aws-sdk-go/releases](https://github.com/aws/aws-sdk-go/releases)). $ cd $GOPATH/src/github.com/aws/aws-sdk-go $ git fetch $ go checkout v1.34.0 After you upgrade your dependencies and verify, deploy the application to your fleet. Once the rollout is complete, you can migrate your V1 encryption and decryption clients to V2. ## Migrate Encryption and Decryption Clients to V2 After updating your existing clients to read the new encryption formats, you can now proceed with safely updating your applications to the V2 encryption and decryption clients. The next series of steps will guide you through successfully migrating your code from V1 to V2. ### Migrate Cipher Data Generators Applications that use [NewKMSKeyGenerator](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#NewKMSKeyGenerator) or [NewKMSKeyGeneratorWithMatDesc](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#NewKMSKeyGeneratorWithMatDesc) functions for constructing a [CipherDataGenerator](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#CipherDataGenerator) need to migrate their usage to [NewKMSContextKeyGenerator](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#NewKMSContextKeyGenerator). This migration is required because support for the former `CipherDataGenerators` have been deprecated. Attempting to construct a V2 client using the old methods will result in an error during client construction. **Example: Migrate NewKMSKeyGenerator** _Pre-migration_ sess := session.Must(session.NewSession()) kmsClient := kms.New(sess) cmkID := "1234abcd-12ab-34cd-56ef-1234567890ab" cipherDataGenerator := s3crypto.NewKMSKeyGenerator(kmsClient, cmkID) _Post-migration_ sess := session.Must(session.NewSession()) kmsClient := kms.New(sess) cmkID := "1234abcd-12ab-34cd-56ef-1234567890ab" var matDesc s3crypto.MaterialDescription // changed NewKMSKeyGenerator to NewKMSContextKeyGenerator cipherDataGenerator := s3crypto.NewKMSContextKeyGenerator(kmsClient, cmkID, matDesc) **Example: Migrate NewKMSKeyGeneratorWithMatDesc** _Pre-migration_ sess := session.Must(session.NewSession()) kmsClient := kms.New(sess) cmkID := "1234abcd-12ab-34cd-56ef-1234567890ab" matDesc := s3crypto.MaterialDescription{ "custom-key": aws.String("custom value"), } cipherDataGenerator := s3crypto.NewKMSKeyGeneratorWithMatDesc(kmsClient, cmkID, matDesc) _Post-migration_ sess := session.Must(session.NewSession()) kmsClient := kms.New(sess) cmkID := "1234abcd-12ab-34cd-56ef-1234567890ab" matDesc := s3crypto.MaterialDescription{ "custom-key": aws.String("custom value"), } // changed NewKMSKeyGeneratorWithMatDesc to NewKMSContextKeyGenerator cipherDataGenerator := s3crypto.NewKMSContextKeyGenerator(kmsClient, cmkID, matDesc) ### Migrate Content Cipher Builders Applications that use [AESCBCContentCipherBuilder](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#AESCBCContentCipherBuilder) to construct an AES/CBC content cipher must migrate to AES/GCM using [AESGCMContentCipherBuilderV2](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#AESGCMContentCipherBuilderV2). Applications that use [AESGCMContentCipherBuilder](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#AESGCMContentCipherBuilder) to construct the AES/GCM content cipher must migrate to [AESGCMContentCipherBuilderV2](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#AESGCMContentCipherBuilderV2). Attempting to use the deprecated content cipher builders with the V2 encryption client will result in a runtime error during the client construction. ###### Important Due to limitations in the Go standard library, objects must be read into memory when performing encryption and decryption operations using AES/GCM. Caution must be taken to ensure that your application does not experience memory allocation failures. **Example: Migrate AESCBCContentCipherBuilder** _Pre-migration_ contentCipherBuilder := s3crypto.AESCBCContentCipherBuilder(cipherDataGenerator, s3crypto.AESCBCPadder) _Post-migration_ contentCipherBuilder := s3crypto.AESGCMContentCipherBuilderV2(cipherDataGenerator) **Example: Migrate AESGCMContentCipherBuilder** _Pre-migration_ contentCipherBuilder := s3crypto.AESGCMContentCipherBuilder(cipherDataGenerator, s3crypto.AESCBCPadder) _Post-migration_ contentCipherBuilder := s3crypto.AESGCMContentCipherBuilderV2(cipherDataGenerator) ### Migrate Encryption Client Constructors The V2 encryption client constructor adds an error interface type as an additional return parameter. An error can be returned during V2 client construction if the client is given a deprecated [ContentCipherBuilder](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#ContentCipherBuilder) or [CipherDataGenerator](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#CipherDataGenerator). Review the migration steps required to migrate these types. **Example** _Pre-migration_ encryptionClient := s3crypto.NewEncryptionClient(sess, contentCipherBuilder) _Post-migration_ encryptionClient, err := s3crypto.NewEncryptionClientV2(sess, contentCipherBuilder) if err != nil { panic(err) } ### Migrate Custom Encryption Client Configurations Clients that utilize custom client configuration options will be required to update their function argument signatures to use [EncryptionClientOptions](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#EncryptionClientOptions) for setting custom options such as an alternative [SaveStrategy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#SaveStrategy). **Pre-migration** // example setting an alternative SaveStrategy encryptionClient := s3crypto.NewEncryptionClient(cipherDataGenerator, contentCipherBuilder, func(o *s3crypto.EncryptionClient) { // Set Instruction File Save Strategy o.SaveStrategy = s3crypto.S3SaveStrategy{Client: s3.New(sess)} }) **Post-migration** // example setting an alternative SaveStrategy encryptionClient, err := s3crypto.NewEncryptionClientV2(sess, contentCipherBuilder, func(o *s3crypto.EncryptionClientOptions) { // Set Instruction File Save Strategy o.SaveStrategy = s3crypto.S3SaveStrategy{Client: s3.New(sess)} }) if err != nil { panic(err) } ### Migrate Decryption Client Constructors The V2 decryption client now requires that an application registers the content ciphers and key wrapping algorithms that it wants to decrypt. This is registration is done using the [CryptoRegistry](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#CryptoRegistry), and a series of registration helper functions are included to enable the V2 decryption client to decrypt objects written in either the V1 or V2 encryption formats. **Step 1: Instantiate a CryptoRegistry** registry := s3crypto.NewCryptoRegistry() **Step 2: Register required content decryption algorithms** _To read content encrypted using V1 AESGCMContentCipherBuilder or V2 AESGCMContentCipherBuilderV2:_ if err := s3crypto.RegisterAESGCMContentCipher(registry); err != nil { panic(err) } _To read content encrypted using V1 AESCBCContentCipherBuilder:_ padder := s3crypto.AESCBCPadder // Use the padder provided to AESCBCContentCipherBuilder if err := s3crypto.RegisterAESCBCContentCipher(registry, padder); err != nil { panic(err) } _To read custom content cipher implementations:_ If your applications implements or uses a custom content cipher implementation, you may register that implementation using the CryptoRegistry’s [AddCEK](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#CryptoRegistry.AddCEK) method. If you require custom padders for your cipher, they can be registered using [AddPadder](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#CryptoRegistry.AddPadder). if err := registry.AddCEK("CustomCEK", NewCustomCEK); err != nil { panic(err) } if err := registry.AddPadder("CustomPadder", NewCustomPadder); err != nil { panic(err) } **Step 3: Register required key wrapping algorithms** _To read keys created using the V2 NewKMSContextKeyGenerator:_ Your application can opt to limit the CMK that is used when calling the KMS `Decrypt` API. Two registration functions allow the selection of the desired behavior. [RegisterKMSContextWrapWithCMK](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#RegisterKMSContextWrapWithCMK) and [RegisterKMSContextWrapWithAnyCMK](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#RegisterKMSContextWrapWithAnyCMK). Only one of these two methods should be used, and attempting to use both functions with a single registry will result in a runtime error. // Use RegisterKMSContextWrapWithCMK to limit the KMS Decrypt to a single CMK if err := s3crypto.RegisterKMSContextWrapWithCMK(registry, kms.New(sess), "key-id"); err != nil { panic(err) } // Use RegisterKMSContextWrapWithAnyCMK to allow the KMS Decrypt call for any CMK if err := s3crypto.RegisterKMSContextWrapWithAnyCMK(registry, kms.New(sess)); err != nil { panic(err) } _To read keys created using the V1 NewKMSKeyGenerator or NewKMSKeyGeneratorWithMatDesc:_ Your application can opt to limit the CMK that is used when calling the KMS Decrypt API. Two registration functions allow the selection of the desired behavior. [RegisterKMSWrapWithCMK](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#RegisterKMSWrapWithCMK) and [RegisterKMSWrapWithAnyCMK](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#RegisterKMSWrapWithAnyCMK). Use only one of these methods. Attempting to register both functions into the registry will result in a runtime error. // Use RegisterKMSWrapWithCMK to limit the KMS Decrypt Call to a single CMK if err := s3crypto.RegisterKMSWrapWithCMK(registry, kms.New(sess), "key-id"); err != nil { panic(err) } // Use RegisterKMSWrapWithAnyCMK to allow KMS Decrypt call for any CMK if err := s3crypto.RegisterKMSWrapWithAnyCMK(registry, kms.New(sess)); err != nil { panic(err) } _To read custom key wrapping algorithm implementations:_ If your applications implements or uses a custom key wrapping implementation, you may register that implementation using the CryptoRegistry’s [AddWrap](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#CryptoRegistry.AddWrap) method. if err := registry.AddWrap("CustomWrap", NewCustomWrap); err != nil { panic(err) } **Step 4: Construct the client** After registering your applications required content decryption and key wrapping algorithms to the CryptoRegistry, you can now construct a V2 decryption client using [NewDecryptionClientV2](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#NewDecryptionClientV2). decryptionClient, err := s3crypto.NewDecryptionClientV2(sess, registry) if err != nil { panic(err) } ### Migrating Custom Decryption Client Configurations Clients that use custom client configuration options are required to update their functional argument signatures to use [DecryptionClientOptions](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#DecryptionClientOptions) for setting custom options, such as an alternative [LoadStrategy](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/#LoadStrategy). **Example** _Pre-migration_ // example setting an alternative LoadStrategy decryptionClient := s3crypto.NewDecryptionClient(sess, func(o *s3crypto.DecryptionClient) { // Set Instruction File Load Strategy o.LoadStrategy = s3crypto.S3LoadStrategy{Client: s3.New(sess)} }) _Post-migration_ // example setting an alternative LoadStrategy decryptionClient, err := s3crypto.NewDecryptionClientV2(sess, registry, func(o *s3crypto.DecryptionClientOptions) { // Set Instruction File Load Strategy o.LoadStrategy = s3crypto.S3LoadStrategy{Client: s3.New(sess)} }) if err != nil { panic(err) } After you complete this migration, you can proceed to testing and deployment using your application’s best practices. After deploying your application deployment, you will have successfully migrated it from the V1 to V2 Amazon S3 encryption clients. ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Enforcing a minimum TLS version Document History Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/sdk-utilities.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#sdk-utilities "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Amazon CloudFront URL SignerAmazon DynamoDB Attributes ConverterAmazon Elastic Compute Cloud MetadataAmazon S3 Transfer Managers 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/). # Using the AWS SDK for Go Utilities The AWS SDK for Go includes the following utilities to help you more easily use AWS services. Find the SDK utilities in their related AWS service package. ## Amazon CloudFront URL Signer The Amazon CloudFront URL signer simplifies the process of creating signed URLs. A signed URL includes information, such as an expiration date and time, that enables you to control access to your content. Signed URLs are useful when you want to distribute content through the internet, but want to restrict access to certain users (for example, to users who have paid a fee). To sign a URL, create a `URLSigner` instance with your CloudFront key pair ID and the associated private key. Then call the `Sign` or `SignWithPolicy` method and include the URL to sign. For more information about Amazon CloudFront key pairs, see [Creating CloudFront Key Pairs for Your Trusted Signers](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html#private-content-creating-cloudfront-key-pairs) in the Amazon CloudFront Developer Guide. The following example creates a signed URL that’s valid for one hour after it is created. signer := sign.NewURLSigner(keyID, privKey) signedURL, err := signer.Sign(rawURL, time.Now().Add(1*time.Hour)) if err != nil { log.Fatalf("Failed to sign url, err: %s\n", err.Error()) return } For more information about the signing utility, see the [sign](https://docs.aws.amazon.com/sdk-for-go/api/service/cloudfront/sign/) package in the AWS SDK for Go API Reference. ## Amazon DynamoDB Attributes Converter The attributes converter simplifies converting Amazon DynamoDB attribute values to and from concrete Go types. Conversions make it easy to work with attribute values in Go and to write values to Amazon DynamoDB tables. For example, you can create records in Go and then use the converter when you want to write those records as attribute values to a DynamoDB table. The following example converts a structure to an Amazon DynamoDB`AttributeValues` map and then puts the data to the `exampleTable`. type Record struct { MyField string Letters []string A2Num map[string]int } r := Record{ MyField: "dynamodbattribute.ConvertToX example", Letters: []string{"a", "b", "c", "d"}, A2Num: map[string]int{"a": 1, "b": 2, "c": 3}, } //... svc := dynamodb.New(session.New(&aws.Config{Region: aws.String("us-west-2")})) item, err := dynamodbattribute.ConvertToMap(r) if err != nil { fmt.Println("Failed to convert", err) return } result, err := svc.PutItem(&dynamodb.PutItemInput{ Item: item, TableName: aws.String("exampleTable"), }) fmt.Println("Item put to dynamodb", result, err) For more information about the converter utility, see the [dynamodbattribute](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/) package in the AWS SDK for Go API Reference. ## Amazon Elastic Compute Cloud Metadata `EC2Metadata` is a client that interacts with the Amazon EC2 metadata service. The client can help you easily retrieve information about instances on which your applications run, such as its region or local IP address. Typically, you must create and submit HTTP requests to retrieve instance metadata. Instead, create an `EC2Metadata` service client. c := ec2metadata.New(session.New()) Then use the service client to retrieve information from a metadata category like `local-ipv4` (the private IP address of the instance). localip, err := c.GetMetadata("local-ipv4") if err != nil { log.Printf("Unable to retrieve the private IP address from the EC2 instance: %s\n", err) return } For a list of all metadata categories, see [Instance Metadata Categories](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories) in the Amazon EC2 User Guide. ### Retrieving an Instance’s Region There’s no instance metadata category that returns only the region of an instance. Instead, use the included `Region` method to easily return an instance’s region. region, err := ec2metadata.New(session.New()).Region() if err != nil { log.Printf("Unable to retrieve the region from the EC2 instance %v\n", err) } For more information about the EC2 metadata utility, see the [ec2metadata](https://docs.aws.amazon.com/sdk-for-go/api/aws/ec2metadata/) package in the AWS SDK for Go API Reference. ## Amazon S3 Transfer Managers The Amazon Simple Storage Service upload and download managers can break up large objects so they can be transferred in multiple parts, in parallel. This makes it easy to resume interrupted transfers. ### Upload Manager The Amazon Simple Storage Service upload manager determines if a file can be split into smaller parts and uploaded in parallel. You can customize the number of parallel uploads and the size of the uploaded parts. #### Example: Uploading a File The following example uses the Amazon S3 `Uploader` to upload a file. Using `Uploader` is similar to the `s3.PutObject()` operation. mySession, _ := session.NewSession() uploader := s3manager.NewUploader(mySession) result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: &uploadBucket, Key: &uploadFileKey, Body: uploadFile, }) #### Configuration Options When you instantiate an `Uploader` instance, you can specify several configuration options (`UploadOptions`) to customize how objects are uploaded: * `PartSize`– Specifies the buffer size, in bytes, of each part to upload. The minimum size per part is 5 MB. * `Concurrency`– Specifies the number of parts to upload in parallel. * `LeavePartsOnError`– Indicates whether to leave successfully uploaded parts in Amazon S3. Tweak the `PartSize` and `Concurrency` configuration values to find the optimal configuration. For example, systems with high-bandwidth connections can send bigger parts and more uploads in parallel. For more information about `Uploader` and its configurations, see the [s3manager](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Uploader) package in the AWS SDK for Go API Reference. #### UploadInput Body Field (io.ReadSeeker vs. io.Reader) The `Body` field of the `s3manager.UploadInput` struct is an `io.Reader` type. However, the field also satisfies the `io.ReadSeeker` interface. For `io.ReadSeeker` types, the `Uploader` doesn’t buffer the body contents before sending it to Amazon S3. `Uploader` calculates the expected number of parts before uploading the file to Amazon S3. If the current value of `PartSize` requires more than 10,000 parts to upload the file, `Uploader` increases the part size value so that fewer parts are required. For `io.Reader` types, the bytes of the reader must buffer each part in memory before the part is uploaded. When you increase the `PartSize` or `Concurrency` value, the required memory (RAM) for the `Uploader` increases significantly. The required memory is approximately _``PartSize``_ * _``Concurrency``_. For example, if you specify 100 MB for `PartSize` and 10 for `Concurrency`, the required memory will be at least 1 GB. Because an `io.Reader` type cannot determine its size before reading its bytes, `Uploader` cannot calculate how many parts must be uploaded. Consequently, `Uploader` can reach the Amazon S3 upload limit of 10,000 parts for large files if you set the `PartSize` too low. If you try to upload more than 10,000 parts, the upload stops and returns an error. #### Handling Partial Uploads If an upload to Amazon S3 fails, by default, `Uploader` uses the Amazon S3`AbortMultipartUpload` operation to remove the uploaded parts. This functionality ensures that failed uploads do not consume Amazon S3 storage. You can set `LeavePartsOnError` to true so that the `Uploader` doesn’t delete successfully uploaded parts. This is useful for resuming partially completed uploads. To operate on uploaded parts, you must get the `UploadID` of the failed upload. The following example demonstrates how to use the `s3manager.MultiUploadFailure` message to get the `UploadID`. u := s3manager.NewUploader(session.New()) output, err := u.upload(input) if err != nil { if multierr, ok := err.(s3manager.MultiUploadFailure); ok { // Process error and its associated uploadID fmt.Println("Error:", multierr.Code(), multierr.Message(), multierr.UploadID()) } else { // Process error generically fmt.Println("Error:", err.Error()) } } #### Example: Upload a Folder to Amazon S3 The following example uses the `path/filepath` package to recursively gather a list of files and upload them to the specified Amazon S3 bucket. The keys of the Amazon S3 objects are prefixed with the file’s relative path. package main import ( "log" "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/s3/s3manager" ) var ( localPath string bucket string prefix string ) func init() { if len(os.Args) != 4 { log.Fatalln("Usage:", os.Args[0], " ") } localPath = os.Args[1] bucket = os.Args[2] prefix = os.Args[3] } func main() { walker := make(fileWalk) go func() { // Gather the files to upload by walking the path recursively if err := filepath.Walk(localPath, walker.Walk); err != nil { log.Fatalln("Walk failed:", err) } close(walker) }() // For each file found walking, upload it to S3 uploader := s3manager.NewUploader(session.New()) for path := range walker { rel, err := filepath.Rel(localPath, path) if err != nil { log.Fatalln("Unable to get relative path:", path, err) } file, err := os.Open(path) if err != nil { log.Println("Failed opening file", path, err) continue } defer file.Close() result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: &bucket, Key: aws.String(filepath.Join(prefix, rel)), Body: file, }) if err != nil { log.Fatalln("Failed to upload", path, err) } log.Println("Uploaded", path, result.Location) } } type fileWalk chan string func (f fileWalk) Walk(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { f <- path } return nil } #### Example: Upload a File to Amazon S3 and Send its Location to Amazon SQS The following example uploads a file to an Amazon S3 bucket and then sends a notification message of the file’s location to an Amazon Simple Queue Service queue. package main import ( "log" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/service/sqs" ) // Uploads a file to a specific bucket in S3 with the file name // as the object's key. After it's uploaded, a message is sent // to a queue. func main() { if len(os.Args) != 4 { log.Fatalln("Usage:", os.Args[0], " ") } file, err := os.Open(os.Args[3]) if err != nil { log.Fatal("Open failed:", err) } defer file.Close() // Upload the file to S3 using the S3 Manager uploader := s3manager.NewUploader(session.New()) uploadRes, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String(os.Args[1]), Key: aws.String(file.Name()), Body: file, }) if err != nil { log.Fatalln("Upload failed:", err) } // Get the URL of the queue that the message will be posted to svc := sqs.New(session.New()) urlRes, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ QueueName: aws.String(os.Args[2]), }) if err != nil { log.Fatalln("GetQueueURL failed:", err) } // Send the message to the queue _, err = svc.SendMessage(&sqs.SendMessageInput{ MessageBody: &uploadRes.Location, QueueUrl: urlRes.QueueUrl, }) if err != nil { log.Fatalln("SendMessage failed:", err) } } ### Download Manager The Amazon S3 download manager determines if a file can be split into smaller parts and downloaded in parallel. You can customize the number of parallel downloads and the size of the downloaded parts. #### Example: Download a File The following example uses the Amazon S3`Downloader` to download a file. Using `Downloader` is similar to the `s3.GetObject()` operation. downloader := s3manager.NewDownloader(session.New()) numBytes, err := downloader.Download(downloadFile, &s3.GetObjectInput{ Bucket: &downloadBucket, Key: &downloadFileKey, }) The `downloadFile` parameter is an `io.WriterAt` type. The `WriterAt` interface enables the `Downloader` to write multiple parts of the file in parallel. #### Configuration Options When you instantiate a `Downloader` instance, you can specify several configuration options (`DownloadOptions`) to customize how objects are downloaded: * `PartSize`– Specifies the buffer size, in bytes, of each part to download. The minimum size per part is 5 MB. * `Concurrency`– Specifies the number of parts to download in parallel. Tweak the `PartSize` and `Concurrency` configuration values to find the optimal configuration. For example, systems with high-bandwidth connections can receive bigger parts and more downloads in parallel. For more information about `Downloader` and its configurations, see the [s3manager](https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Downloader) package in the AWS SDK for Go API Reference. #### Example: Download All Objects in a Bucket The following example uses pagination to gather a list of objects from an Amazon S3 bucket. Then it downloads each object to a local file. package main import ( "fmt" "os" "path/filepath" "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" ) var ( Bucket = "amzn-s3-demo-bucket" // Download from this bucket Prefix = "logs/" // Using this key prefix LocalDirectory = "s3logs" // Into this directory ) func main() { manager := s3manager.NewDownloader(session.New()) d := downloader{bucket: Bucket, dir: LocalDirectory, Downloader: manager} client := s3.New(session.New()) params := &s3.ListObjectsInput{Bucket: &Bucket, Prefix: &Prefix} client.ListObjectsPages(params, d.eachPage) } type downloader struct { *s3manager.Downloader bucket, dir string } func (d *downloader) eachPage(page *s3.ListObjectsOutput, more bool) bool { for _, obj := range page.Contents { d.downloadToFile(*obj.Key) } return true } func (d *downloader) downloadToFile(key string) { // Create the directories in the path file := filepath.Join(d.dir, key) if err := os.MkdirAll(filepath.Dir(file), 0775); err != nil { panic(err) } // Set up the local file fd, err := os.Create(file) if err != nil { panic(err) } defer fd.Close() // Download the file using the AWS SDK for Go fmt.Printf("Downloading s3://%s/%s to %s...\n", d.bucket, key, file) params := &s3.GetObjectInput{Bucket: &d.bucket, Key: &key} d.Download(fd, params) } ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Using Dead Letter Queues in Amazon SQS Security Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/security-iam.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#security-iam "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) AudienceAuthenticating with identitiesManaging access using policiesHow AWS services work with IAMTroubleshooting AWS identity and access 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/). # Identity and Access Management AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be _authenticated_ (signed in) and _authorized_ (have permissions) to use AWS resources. IAM is an AWS service that you can use with no additional charge. ###### Topics * Audience * Authenticating with identities * Managing access using policies * How AWS services work with IAM * Troubleshooting AWS identity and access ## Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in AWS. **Service user** – If you use AWS services to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more AWS features to do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in AWS, see Troubleshooting AWS identity and access or the user guide of the AWS service you are using. **Service administrator** – If you're in charge of AWS resources at your company, you probably have full access to AWS. It's your job to determine which AWS features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page to understand the basic concepts of IAM. To learn more about how your company can use IAM with AWS, see the user guide of the AWS service you are using. **IAM administrator** – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to AWS. To view example AWS identity-based policies that you can use in IAM, see the user guide of the AWS service you are using. ## Authenticating with identities Authentication is how you sign in to AWS using your identity credentials. You must be authenticated as the AWS account root user, an IAM user, or by assuming an IAM role. You can sign in as a federated identity using credentials from an identity source like AWS IAM Identity Center (IAM Identity Center), single sign-on authentication, or Google/Facebook credentials. For more information about signing in, see [How to sign in to your AWS account](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the _AWS Sign-In User Guide_. For programmatic access, AWS provides an SDK and CLI to cryptographically sign requests. For more information, see [AWS Signature Version 4 for API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) in the _IAM User Guide_. ### AWS account root user When you create an AWS account, you begin with one sign-in identity called the AWS account _root user_ that has complete access to all AWS services and resources. We strongly recommend that you don't use the root user for everyday tasks. For tasks that require root user credentials, see [Tasks that require root user credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks) in the _IAM User Guide_. ### Federated identity As a best practice, require human users to use federation with an identity provider to access AWS services using temporary credentials. A _federated identity_ is a user from your enterprise directory, web identity provider, or Directory Service that accesses AWS services using credentials from an identity source. Federated identities assume roles that provide temporary credentials. For centralized access management, we recommend AWS IAM Identity Center. For more information, see [What is IAM Identity Center?](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) in the _AWS IAM Identity Center User Guide_. ### IAM users and groups An _[IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)_ is an identity with specific permissions for a single person or application. We recommend using temporary credentials instead of IAM users with long-term credentials. For more information, see [Require human users to use federation with an identity provider to access AWS using temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) in the _IAM User Guide_. An [_IAM group_](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) specifies a collection of IAM users and makes permissions easier to manage for large sets of users. For more information, see [Use cases for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/gs-identities-iam-users.html) in the _IAM User Guide_. ### IAM roles An _[IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)_ is an identity with specific permissions that provides temporary credentials. You can assume a role by [switching from a user to an IAM role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html) or by calling an AWS CLI or AWS API operation. For more information, see [Methods to assume a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage-assume.html) in the _IAM User Guide_. IAM roles are useful for federated user access, temporary IAM user permissions, cross-account access, cross-service access, and applications running on Amazon EC2. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the _IAM User Guide_. ## Managing access using policies You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy defines permissions when associated with an identity or resource. AWS evaluates these policies when a principal makes a request. Most policies are stored in AWS as JSON documents. For more information about JSON policy documents, see [Overview of JSON policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json) in the _IAM User Guide_. Using policies, administrators specify who has access to what by defining which **principal** can perform **actions** on what **resources** , and under what **conditions**. By default, users and roles have no permissions. An IAM administrator creates IAM policies and adds them to roles, which users can then assume. IAM policies define permissions regardless of the method used to perform the operation. ### Identity-based policies Identity-based policies are JSON permissions policy documents that you attach to an identity (user, group, or role). These policies control what actions identities can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the _IAM User Guide_. Identity-based policies can be _inline policies_ (embedded directly into a single identity) or _managed policies_ (standalone policies attached to multiple identities). To learn how to choose between managed and inline policies, see [Choose between managed policies and inline policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-choosing-managed-or-inline.html) in the _IAM User Guide_. ### Resource-based policies Resource-based policies are JSON policy documents that you attach to a resource. Examples include IAM _role trust policies_ and Amazon S3 _bucket policies_. In services that support resource-based policies, service administrators can use them to control access to a specific resource. You must [specify a principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) in a resource-based policy. Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy. ### Access control lists (ACLs) Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see [Access control list (ACL) overview](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html) in the _Amazon Simple Storage Service Developer Guide_. ### Other policy types AWS supports additional policy types that can set the maximum permissions granted by more common policy types: * **Permissions boundaries** – Set the maximum permissions that an identity-based policy can grant to an IAM entity. For more information, see [Permissions boundaries for IAM entities](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) in the _IAM User Guide_. * **Service control policies (SCPs)** – Specify the maximum permissions for an organization or organizational unit in AWS Organizations. For more information, see [Service control policies](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) in the _AWS Organizations User Guide_. * **Resource control policies (RCPs)** – Set the maximum available permissions for resources in your accounts. For more information, see [Resource control policies (RCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_rcps.html) in the _AWS Organizations User Guide_. * **Session policies** – Advanced policies passed as a parameter when creating a temporary session for a role or federated user. For more information, see [Session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) in the _IAM User Guide_. ### Multiple policy types When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see [Policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html) in the _IAM User Guide_. ## How AWS services work with IAM To get a high-level view of how AWS services work with most IAM features, see [AWS services that work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) in the _IAM User Guide_. To learn how to use a specific AWS service with IAM, see the security section of the relevant service's User Guide. ## Troubleshooting AWS identity and access Use the following information to help you diagnose and fix common issues that you might encounter when working with AWS and IAM. ###### Topics * I am not authorized to perform an action in AWS * I am not authorized to perform iam:PassRole * I want to allow people outside of my AWS account to access my AWS resources ### I am not authorized to perform an action in AWS If you receive an error that you're not authorized to perform an action, your policies must be updated to allow you to perform the action. The following example error occurs when the `mateojackson` IAM user tries to use the console to view details about a fictional ``my-example-widget`` resource but doesn't have the fictional `awes:`GetWidget`` permissions. User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: awes:GetWidget on resource: my-example-widget In this case, the policy for the `mateojackson` user must be updated to allow access to the ``my-example-widget`` resource by using the `awes:`GetWidget`` action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. ### I am not authorized to perform iam:PassRole If you receive an error that you're not authorized to perform the `iam:PassRole` action, your policies must be updated to allow you to pass a role to AWS. Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service. The following example error occurs when an IAM user named `marymajor` tries to use the console to perform an action in AWS. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service. User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole In this case, Mary's policies must be updated to allow her to perform the `iam:PassRole` action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. ### I want to allow people outside of my AWS account to access my AWS resources You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources. To learn more, consult the following: * To learn whether AWS supports these features, see How AWS services work with IAM. * To learn how to provide access to your resources across AWS accounts that you own, see [Providing access to an IAM user in another AWS account that you own](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html) in the _IAM User Guide_. * To learn how to provide access to your resources to third-party AWS accounts, see [Providing access to AWS accounts owned by third parties](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_third-party.html) in the _IAM User Guide_. * To learn how to provide access through identity federation, see [Providing access to externally authenticated users (identity federation)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_common-scenarios_federated-users.html) in the _IAM User Guide_. * To learn the difference between using roles and resource-based policies for cross-account access, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the _IAM User Guide_. ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Data Protection Compliance Validation Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/security.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#security "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # Security for this AWS Product or Service Cloud security at Amazon Web Services (AWS) is the highest priority. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The [Shared Responsibility Model](https://aws.amazon.com/compliance/shared-responsibility-model/) describes this as Security of the Cloud and Security in the Cloud. **Security of the Cloud** – AWS is responsible for protecting the infrastructure that runs all of the services offered in the AWS Cloud and providing you with services that you can use securely. Our security responsibility is the highest priority at AWS, and the effectiveness of our security is regularly tested and verified by third-party auditors as part of the [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/). **Security in the Cloud** – Your responsibility is determined by the AWS service you are using, and other factors including the sensitivity of your data, your organization’s requirements, and applicable laws and regulations. This AWS product or service follows the [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) through the specific Amazon Web Services (AWS) services it supports. For AWS service security information, see the [AWS service security documentation page](https://docs.aws.amazon.com/security/?id=docs_gateway#aws-security) and [AWS services that are in scope of AWS compliance efforts by compliance program](https://aws.amazon.com/compliance/services-in-scope/). ###### Topics * [Data Protection](./data-protection.html) * [Identity and Access Management](./security-iam.html) * [Compliance Validation](./compliance-validation.html) * [Resilience](./disaster-recovery-resiliency.html) * [Infrastructure Security](./infrastructure-security.html) * [Enforcing a minimum TLS version](./tls.html) * [S3 Encryption Client Migration](./s3-encryption-migration.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) SDK Utilities Data Protection Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/sessions.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#sessions "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) ConcurrencySessions with a Shared Configuration FileCreating SessionsCreate Sessions with Option OverridesEnvironment VariablesAdding Request HandlersCopying a Session 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/). # Using Sessions to Configure Service Clients in the AWS SDK for Go In the AWS SDK for Go, a session is an object that contains configuration information for [service clients](./making-requests.html). which you use to interact with AWS services. For example, sessions can include information about the region where requests will be sent, which credentials to use, or additional request handlers. Whenever you create a service client, you must specify a session. For more information about sessions, see the [session](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/) package in the AWS SDK for Go API Reference. Sessions can be shared across all service clients that share the same base configuration. The session is built from the SDK’s default configuration and request handlers. You should cache sessions when possible. This is because creating a new session loads all configuration values from the environment and configuration files each time the session is created. Sharing the session value across all of your service clients ensures the configuration is loaded the fewest number of times. ## Concurrency Sessions are safe to use concurrently as long as the session isn’t being modified. The SDK doesn’t modify the session once the session is created. Creating service clients concurrently from a shared session is safe. ## Sessions with a Shared Configuration File Using the previous method, you can create sessions that load the additional configuration file only if the `AWS_SDK_LOAD_CONFIG` environment variable is set. Alternatively you can explicitly create a session with a shared configuration enabled. To do this, you can use `NewSessionWithOptions` to configure how the session is created. Using the `NewSessionWithOptions` with `SharedConfigState` set to `SharedConfigEnable` will create the session as if the `AWS_SDK_LOAD_CONFIG` environment variable was set. ## Creating Sessions When you create a `session`, you can pass in optional `aws.Config` values that override the default or that override the current configuration values. This allows you to provide additional or case-based configuration as needed. By default `NewSession` only loads credentials from the shared credentials file (`~/.aws/credentials`). If the `AWS_SDK_LOAD_CONFIG` environment variable is set to a truthy value, the session is created from the configuration values from the shared configuration (`~/.aws/config`) and shared credentials (`~/.aws/credentials`) files. See Sessions with a Shared Configuration File for more information. Create a session with the default configuration and request handlers. The following example creates a session with credentials, region, and profile values from either the environment variables or the shared credentials file. It requires that the `AWS_PROFILE` is set, or `default` is used. sess, err := session.NewSession() The SDK provides a [default configuration](https://docs.aws.amazon.com/sdk-for-go/api/aws/defaults/) that all sessions use, unless you override a field. For example, you can specify an AWS Region when you create a session by using the `aws.Config` struct. For more information about the fields you can specify, see the [aws.Config](https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config) in the AWS SDK for Go API Reference. sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-east-2")}, ) Create an Amazon S3 client instance from a session: sess, err := session.NewSession() if err != nil { // Handle Session creation error } svc := s3.New(sess) ## Create Sessions with Option Overrides In addition to `NewSession`, you can create sessions using `NewSessionWithOptions`. This function allows you to control and override how the session will be created through code, instead of being driven by environment variables only. Use [NewSessionWithOptions](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/#NewSessionWithOptions) when you want to provide the config profile, or override the shared credentials state (`AWS_SDK_LOAD_CONFIG`). // Equivalent to session.New sess, err := session.NewSessionWithOptions(session.Options{}) // Specify profile to load for the session's config sess, err := session.NewSessionWithOptions(session.Options{ Profile: "profile_name", }) // Specify profile for config and region for requests sess, err := session.NewSessionWithOptions(session.Options{ Config: aws.Config{Region: aws.String("us-east-2")}, Profile: "profile_name", }) // Force enable Shared Config support sess, err := session.NewSessionWithOptions(session.Options{ SharedConfigState: SharedConfigEnable, }) // Assume an IAM role with MFA prompting for token code on stdin sess := session.Must(session.NewSessionWithOptions(session.Options{ AssumeRoleTokenProvider: stscreds.StdinTokenProvider, SharedConfigState: SharedConfigEnable, })) ### Deprecated `New` The `New` function has been deprecated because it doesn’t provide a good way to return errors that occur when loading the configuration files and values. Because of this, `NewSession` was created so errors can be retrieved when creating a session fails. ### Shared Configuration Fields By default, the SDK loads credentials from the shared credentials file `~/.aws/credentials`. Any other configuration values are provided by the environment variables, SDK defaults, and user-provided `aws.config` values. If the `AWS_SDK_LOAD_CONFIG` environment variable is set, or the **SharedConfigEnable** option is used to create the session (as shown in the following example), additional configuration information is also loaded from the shared configuration file (`~/.aws/config`), if it exists. If any configuration setting value differs between the two files, the value from the shared credentials file (`~/.aws/credentials`) takes precedence. sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) See the [session package’s documentation](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/) for more information on shared credentials setup. ## Environment Variables When a session is created, you can set several environment variables to adjust how the SDK functions, and what configuration data it loads when creating sessions. Environment values are optional. For credentials, you must set both an access key and a secret access key. Otherwise, Go ignores the one you’ve set. All environment variable values are strings unless otherwise noted. See the [session package’s documentation](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/) for more information on environment variable setup. ## Adding Request Handlers You can add handlers to a session for processing HTTP requests. All service clients that use the session inherit the handlers. For example, the following handler logs every request and its payload made by a service client. // Create a session, and add additional handlers for all service // clients created with the Session to inherit. Adds logging handler. sess, err := session.NewSession() sess.Handlers.Send.PushFront(func(r *request.Request) { // Log every request made and its payload logger.Println("Request: %s/%s, Payload: %s", r.ClientInfo.ServiceName, r.Operation, r.Params) }) ## Copying a Session You can use the [Copy](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/#Session.Copy) method to create copies of sessions. Copying sessions is useful when you want to create multiple sessions that have similar settings. Each time you copy a session, you can specify different values for any field. For example, the following snippet copies the `sess` session while overriding the `Region` field to `us-east-2`: usEast2Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-2")}) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Custom HTTP Client Using AWS Services Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/setting-up.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#setting-up "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Get an Amazon AccountInstall the AWS SDK for GoGet your AWS access keysImport Packages 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/). # Getting Started with the AWS SDK for Go The AWS SDK for Go requires Go 1.5 or later. You can view your current version of Go by running the `go version` command. For information about installing or upgrading your version of Go, see [https://golang.org/doc/install](https://golang.org/doc/install). ## Get an Amazon Account Before you can use the AWS SDK for Go, you must have an Amazon account. See [How do I create and activate a new Amazon Web Services account?](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account) for details. ## Install the AWS SDK for Go To install the SDK and its dependencies, run the following Go command. go get -u github.com/aws/aws-sdk-go/... If you set the [Go vendor experiment](https://github.com/aws/aws-sdk-go/blob/main/README.md#installing) environment variable to `1`, you can use the following command to get the SDK. The SDK's runtime dependencies are vendored in the `vendor/` folder. go get -u github.com/aws/aws-sdk-go ## Get your AWS access keys Access keys consist of an _access key ID_ and _secret access key_ , which are used to sign programmatic requests that you make to AWS. If you don't have access keys, you can create them by using the [AWS Management Console](https://console.aws.amazon.com/console/home). We recommend that you use IAM access keys instead of AWS root account access keys. IAM lets you securely control access to AWS services and resources in your AWS account. ###### Note To create access keys, you must have permissions to perform the required IAM actions. For more information, see [Granting IAM User Permission to Manage Password Policy and Credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_delegate-permissions.html) in the IAM User Guide. ### To get your access key ID and secret access key 1. Open the [IAM console](https://console.aws.amazon.com/iam/home). 2. On the navigation menu, choose **Users**. 3. Choose your IAM user name (not the check box). 4. Open the **Security credentials** tab, and then choose **Create access key**. 5. To see the new access key, choose **Show**. Your credentials resemble the following: * Access key ID: `AKIAIOSFODNN7EXAMPLE` * Secret access key: `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` 6. To download the key pair, choose **Download .csv file**. Store the keys in a secure location. ###### Important Keep the keys confidential to protect your AWS account, and never email them. Do not share them outside your organization, even if an inquiry appears to come from AWS or Amazon.com. _No one who legitimately represents Amazon will ever ask you for your secret key._ **Related topics** * [What Is IAM?](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) in IAM User Guide. * [AWS Security Credentials](https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html) in Amazon Web Services General Reference. ## Import Packages After you have installed the SDK, you import AWS packages into your Go applications to use the SDK, as shown in the following example, which imports the AWS, Session, and Amazon S3 libraries: import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) What is the AWS SDK for Go Configuring the SDK Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/tls.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#tls "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) How do I set my TLS version? 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/). # Enforcing a minimum TLS version in the AWS SDK for Go To add increased security when communicating with AWS services, you should configure your client to use TLS 1.2 or later. ###### Note As of [Go 1.18](https://go.dev/doc/go1.18#tls10), the TLS configuration used by the `net/http#Client` defaults to TLS 1.2 as a minimum, and disables support for TLS 1.0 and TLS 1.1. ## How do I set my TLS version? You can set the TLS version to 1.2 using the following code. 1. Create a custom HTTP transport to require a minimum version of TLS 1.2 tr := &http.Transport{ TLSClientConfig: &tls.Config{ MinVersion: tls.VersionTLS12, }, } 2. Configure the transport. // In Go versions earlier than 1.13 err := http2.ConfigureTransport(tr) if err != nil { fmt.Println("Got an error configuring HTTP transport") fmt.Println(err) return } // In Go versions later than 1.13 tr.ForceAttemptHTTP2 = true 3. Create an HTTP client with the configured transport, and use that to create a session. REGION is the AWS Region, such as _us-west-2_. client := http.Client{Transport: tr} sess := session.Must(session.NewSession(&aws.Config{ Region: ®ION, HTTPClient: &client, })) 4. Use the following function to confirm your TLS version. func GetTLSVersion(tr *http.Transport) string { switch tr.TLSClientConfig.MinVersion { case tls.VersionTLS10: return "TLS 1.0" case tls.VersionTLS11: return "TLS 1.1" case tls.VersionTLS12: return "TLS 1.2" case tls.VersionTLS13: return "TLS 1.3" } return "Unknown" } 5. Confirm your TLS version by calling _GetTLSVersion_. if tr, ok := sess.Config.HTTPClient.Transport.(*http.Transport); ok { log.Printf("Client uses %v", GetTLSVersion(tr)) } ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Infrastructure Security S3 Encryption Client Migration Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-cb-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-cb-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 CodeBuild Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Building an AWS CodeBuild Project](./cb-example-build-project.html) * [Listing Your AWS CodeBuild Project Builds](./cb-example-list-builds.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Getting Log Events from CloudWatch Getting Information about All AWS CodeBuild Projects Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-cloudtrail-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-cloudtrail-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 CloudTrail Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Creating a CloudTrail Trail](./cloudtrail-example-create-trail.html) * [Listing CloudTrail Trail Events](./cloudtrail-example-lookup-events.html) * [Deleting a CloudTrail Trail](./cloudtrail-example-delete-trail.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) SDK Request Examples Listing the CloudTrail Trails Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-cloudwatch-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-cloudwatch-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 CloudWatch Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Using Alarms and Alarm Actions in CloudWatch](./cw-example-using-alarm-actions.html) * [Getting Metrics from CloudWatch](./cw-example-getting-metrics.html) * [Sending Events to Amazon CloudWatch Events](./cw-example-sending-events.html) * [Getting Log Events from CloudWatch](./cw-example-getting-log-events.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Deleting a CloudTrail Trail Describing CloudWatch Alarms Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-dynamodb-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-dynamodb-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 DynamoDB Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Creating an Amazon DynamoDB Table](./dynamo-example-create-table.html) * [Creating an Amazon DynamoDB Table Item](./dynamo-example-create-table-item.html) * [Creating Amazon DynamoDB Table Items from a JSON File](./dynamo-example-load-table-items-from-json.html) * [Reading an Amazon DynamoDB Table Item](./dynamo-example-read-table-item.html) * [Getting Amazon DynamoDB Table Items Using Expression Builder](./dynamo-example-scan-table-item.html) * [Updating an Amazon DynamoDB Table Item](./dynamo-example-update-table-item.html) * [Deleting an Amazon DynamoDB Table Item](./dynamo-example-delete-table-item.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Listing Your AWS CodeBuild Project Builds Listing all Amazon DynamoDB Tables Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-ec2-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-ec2-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 EC2 Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Managing Amazon EC2 Instances](./ec2-example-manage-instances.html) * [Working with Amazon EC2 Key Pairs](./ec2-example-working-with-key-pairs.html) * [Using Regions and Availability Zones with Amazon EC2](./ec2-example-regions-availability-zones.html) * [Working with Security Groups in Amazon EC2](./ec2-example-security-groups.html) * [Using Elastic IP Addresses in Amazon EC2](./ec2-example-elastic-ip-addresses.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Deleting an Amazon DynamoDB Table Item Creating Amazon EC2 Instances with Tags or without Block Devices Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-glacier-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-glacier-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) The ScenarioPrerequisitesCreate a VaultUpload an Archive 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 Glacier Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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 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 * You have [set up](./setting-up.html) and [configured](./configuring-sdk.html) 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 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 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 } ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Using Elastic IP Addresses in Amazon EC2 IAM Examples Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-iam-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-iam-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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/). # IAM Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Managing IAM Access Keys](./iam-example-managing-access-keys.html) * [Managing IAM Account Aliases](./iam-example-account-aliases.html) * [Working with IAM Policies](./iam-example-policies.html) * [Working with IAM Server Certificates](./iam-example-server-certificates.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Amazon Glacier Examples Managing IAM Users Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-kms-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-kms-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 Key Management Service Examples Using the AWS SDK for Go 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.html) * [Encrypting Data with AWS Key Management Service](./kms-example-encrypt-data.html) * [Decrypting a Data Blob in AWS Key Management Service](./kms-example-decrypt-blob.html) * [Re-encrypting a Data Blob in AWS Key Management Service](./kms-example-re-encrypt-data.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Working with IAM Server Certificates Creating a CMK in AWS Key Management Service Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-lambda-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-lambda-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 Lambda Examples Using the AWS SDK for Go 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.html) * [Creating a Lambda Function](./lambda-go-example-create-function.html) * [Running a Lambda Function](./lambda-go-example-run-function.html) * [Configuring a Lambda Function to Receive Notifications](./lambda-go-example-configure-function-for-notification.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Re-encrypting a Data Blob in AWS Key Management Service Displaying Information about All Lambda Functions Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-polly-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-polly-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 Polly Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Getting a List of Lexicons](./polly-example-list-lexicons.html) * [Synthesizing Speech](./polly-example-synthesize-speech.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Configuring a Lambda Function to Receive Notifications Getting a List of Voices Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-requests-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-requests-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) Using context.Context with SDK RequestsUsing API Field Setters with SDK Requests 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 Request Examples 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). ## Using context.Context with SDK Requests 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 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), ), ) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Code Examples AWS CloudTrail Examples Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-s3-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-s3-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Creating Pre-Signed URLs for Amazon S3 Buckets](./s3-example-presigned-urls.html) * [Using an Amazon S3 Bucket as a Static Web Host](./s3-example-static-web-host.html) * [Working with Amazon S3 CORS Permissions](./s3-example-cors.html) * [Working with Amazon S3 Bucket Policies](./s3-example-bucket-policy.html) * [Working with Amazon S3 Bucket ACLs](./s3-example-bucket-acls.html) * [Encrypting Amazon S3 Bucket Items](./s3-examples-encryption.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Synthesizing Speech Performing Basic Amazon S3 Bucket Operations Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-ses-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-ses-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 SES Examples Using the AWS SDK for Go 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.html) * [Verifying an Email Address in Amazon SES](./ses-example-send-verification.html) * [Sending a Message to an Email Address in Amazon SES](./ses-example-send-email.html) * [Deleting an Email Address in Amazon SES](./ses-example-delete-address.html) * [Getting Amazon SES Statistics](./ses-example-get-statistics.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Encrypting an Amazon S3 Bucket Object on the Server Using AWS KMS Listing Valid Amazon SES Email Addresses Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-sns-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-sns-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) 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 SNS Examples Using the AWS SDK for Go 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.html) * [Creating an Amazon SNS Topic](./sns-example-create-topic.html) * [List Your Amazon SNS Subscriptions](./sns-example-list-subscriptions.html) * [Subscribe to an Amazon SNS Topic](./sns-example-subscribe.html) * [Sending a Message to All Amazon SNS Topic Subscribers](./sns-example-publish.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Getting Amazon SES Statistics Listing Your Amazon SNS Topics Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-sqs-with-go-sdk.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#using-sqs-with-go-sdk "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/). # Amazon SQS Examples Using the AWS SDK for Go 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.html) and [Configuring the AWS SDK for Go](./configuring-sdk.html). 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.html) * [Sending and Receiving Messages in Amazon SQS](./sqs-example-receive-message.html) * [Managing Visibility Timeout in Amazon SQS Queues](./sqs-example-managing-visibility-timeout.html) * [Enabling Long Polling in Amazon SQS Queues](./sqs-example-enable-long-polling.html) * [Using Dead Letter Queues in Amazon SQS](./sqs-example-dead-letter-queues.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Sending a Message to All Amazon SNS Topic Subscribers Using Amazon SQS Queues Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. --- # Source: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html [](/pdfs/sdk-for-go/v1/developer-guide/aws-sdk-go-dg.pdf#welcome "Open PDF") [Documentation](/index.html)[AWS SDK for Go](/sdk-for-go/index.html)[Developer Guide](welcome.html) More InfoMaintenance and support for SDK major versions 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/). # What is the AWS SDK for Go The AWS SDK for Go provides APIs and utilities that developers can use to build Go applications that use AWS services, such as Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). ###### Note This document is for version 1 of the AWS SDK for Go. If you're looking for version 2 of the SDK, see the [version 2 developer guide](https://aws.github.io/aws-sdk-go-v2/docs/) and the [version 2 SDK API reference](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2). The SDK removes the complexity of coding directly against a web service interface. It hides a lot of the lower-level plumbing, such as authentication, request retries, and error handling. The SDK also includes helpful utilities. For example, the Amazon S3 download and upload manager can automatically break up large objects into multiple parts and transfer them in parallel. Use the AWS SDK for Go Developer Guide to help you install, configure, and use the SDK. The guide provides configuration information, sample code, and an introduction to the SDK utilities. ## More Info * To learn about everything you need before you can start using the AWS SDK for Go, see [Getting Started with the AWS SDK for Go](./setting-up.html). * For code examples, see [AWS SDK for Go Code Examples](./common-examples.html). * You can browse the AWS SDK for Go examples in the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples) repo on GitHub. * To learn about the SDK utilities, see [Using the AWS SDK for Go Utilities](./sdk-utilities.html). * For learn about the types and functionality that the library provides, see the [AWS SDK for Go API Reference](https://docs.aws.amazon.com/sdk-for-go/api/). * To view a video introduction of the SDK and a sample application demonstration, see [AWS SDK for Go: Gophers Get Going with AWS](https://www.youtube.com/watch?v=iOGIKG3EptI&feature=youtu.be) from AWS re:Invent 2015. ## Maintenance and support for SDK major versions ### Maintenance and support for SDK major versions For information about maintenance and support for SDK major versions and their underlying dependencies, see the following in the [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/overview.html): * [AWS SDKs and tools maintenance policy](https://docs.aws.amazon.com/sdkref/latest/guide/maint-policy.html) * [AWS SDKs and tools version support matrix](https://docs.aws.amazon.com/sdkref/latest/guide/version-support-matrix.html) ![Warning](https://d1ge0kk1l5kms0.cloudfront.net/images/G/01/webservices/console/warning.png) **Javascript is disabled or is unavailable in your browser.** To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. [Document Conventions](/general/latest/gr/docconventions.html) Getting Started Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better.