Aws SDK Go DG
Aws SDK Go DG
Aws SDK Go DG
Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
AWS SDK for Go Developer Guide
Table of Contents
AWS SDK for Go ................................................................................................................................ 1
Using the AWS SDK for Go with AWS Cloud9 ................................................................................ 1
More Info .................................................................................................................................. 1
Getting Started .................................................................................................................................. 2
Install the AWS SDK for Go ......................................................................................................... 2
Get your AWS access keys ........................................................................................................... 2
To get your access key ID and secret access key ..................................................................... 2
Import Packages ........................................................................................................................ 3
Configuring the SDK ........................................................................................................................... 4
Creating a Session ...................................................................................................................... 4
Specifying the AWS Region ......................................................................................................... 4
Specifying Credentials ................................................................................................................ 5
IAM Roles for Amazon EC2 Instances .................................................................................... 6
Shared Credentials File ....................................................................................................... 6
Environment Variables ........................................................................................................ 7
Hard-Coded Credentials in an Application (Not Recommended) ................................................ 8
Other Credentials Providers ................................................................................................. 8
Configuring a Proxy .................................................................................................................... 8
Logging Service Calls .................................................................................................................. 8
Creating a Custom Endpoint ........................................................................................................ 9
SDK Metrics ............................................................................................................................... 9
Authorize SDK Metrics ........................................................................................................ 9
Set Up SDK Metrics .......................................................................................................... 12
SDK Metric Definitions ...................................................................................................... 14
Custom HTTP Client ................................................................................................................. 15
Dialer.KeepAlive ............................................................................................................... 16
Dialer.Timeout .................................................................................................................. 16
Transport.ExpectContinueTimeout ...................................................................................... 16
Transport.IdleConnTimeout ................................................................................................ 16
Transport.MaxIdleConns .................................................................................................... 17
Transport.MaxIdleConnsPerHost ......................................................................................... 17
Transport.ResponseHeaderTimeout ..................................................................................... 17
Transport.TLSHandshakeTimeout ........................................................................................ 17
Create Import Statement .................................................................................................. 18
Creating a Timeout Struct ................................................................................................. 18
Creating a Function to Create a Custom HTTP Client ............................................................ 18
Using a Custom HTTP Client .............................................................................................. 19
Using Cloud9 with the SDK ............................................................................................................... 20
Step 1: Set up Your AWS Account to Use AWS Cloud9 ................................................................... 20
Step 2: Set up Your AWS Cloud9 Development Environment .......................................................... 20
Step 3: Set up the AWS SDK for Go ............................................................................................ 20
Step 4: Download Example Code ................................................................................................ 21
Step 5: Run Example Code ........................................................................................................ 22
Using Sessions ................................................................................................................................. 23
Concurrency ............................................................................................................................. 23
Sessions with a Shared Configuration File ................................................................................... 23
Creating Sessions ..................................................................................................................... 23
Create Sessions with Option Overrides ........................................................................................ 24
Deprecated New ............................................................................................................... 24
Shared Configuration Fields ............................................................................................... 25
Environment Variables ................................................................................................................ 7
Adding Request Handlers .......................................................................................................... 25
Copying a Session .................................................................................................................... 25
Using AWS Services .......................................................................................................................... 26
iii
AWS SDK for Go Developer Guide
iv
AWS SDK for Go Developer Guide
v
AWS SDK for Go Developer Guide
Using the AWS SDK for Go with AWS Cloud9
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.
See Using AWS Cloud9 with the AWS SDK for Go (p. 20) for information on using AWS Cloud9 with
the AWS SDK for Go.
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 (p. 2).
• For code examples, see AWS SDK for Go Code Examples (p. 36).
• To learn about the SDK utilities, see Using the AWS SDK for Go Utilities (p. 194).
• For learn about the types and functionality that the library provides, see the AWS SDK for Go API
Reference.
• To view a video introduction of the SDK and a sample application demonstration, see AWS SDK For Go:
Gophers Get Going with AWS from AWS re:Invent 2015.
1
AWS SDK for Go Developer Guide
Install the AWS SDK for Go
go get -u github.com/aws/aws-sdk-go/...
If you set the Go vendor experiment 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
in a secure location.
2
AWS SDK for Go Developer Guide
Import Packages
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
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"
)
3
AWS SDK for Go Developer Guide
Creating a Session
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.
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,
}))
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
)
// ...
4
AWS SDK for Go Developer Guide
Specifying Credentials
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
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 (p. 2).
When you initialize a new service client without providing any credential arguments, the SDK uses the
default credential provider chain 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 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 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.
5
AWS SDK for Go Developer Guide
IAM Roles for Amazon EC2 Instances
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.
3. Use environment variables.
Setting environment variables is useful if you're doing development work on a machine other than an
Amazon EC2 instance.
4. Hard-code credentials (not recommended).
Hard-coding credentials in your application can make it difficult to manage and rotate those
credentials. Use this method only for small personal scripts or testing purposes. Do not submit code
with credentials to source control.
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.
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.
[default]
aws_access_key_id = <YOUR_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_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 = <YOUR_TEMP_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_TEMP_SECRET_ACCESS_KEY>
aws_session_token = <YOUR_SESSION_TOKEN>
6
AWS SDK for Go Developer Guide
Environment Variables
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 = <YOUR_DEFAULT_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_DEFAULT_SECRET_ACCESS_KEY>
[test-account]
aws_access_key_id = <YOUR_TEST_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_TEST_SECRET_ACCESS_KEY>
[prod-account]
; work profile
aws_access_key_id = <YOUR_PROD_ACCESS_KEY_ID>
aws_secret_access_key = <YOUR_PROD_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.
_, err := sess.Config.Credentials.Get()
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.
• AWS_ACCESS_KEY_ID
• AWS_SECRET_ACCESS_KEY
• AWS_SESSION_TOKEN (optional)
7
AWS SDK for Go Developer Guide
Hard-Coded Credentials in an
Application (Not Recommended)
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
You can hard-code credentials in your application by passing the access keys to a configuration instance,
as shown in the following snippet.
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 struct
to specify a custom HTTP client. For more information about how to create an HTTP client to use a
proxy, see the Transport struct in the Go http package.
8
AWS SDK for Go Developer Guide
Creating a Custom Endpoint
As telemetry is collected on each host, it is relayed via UDP to localhost, where the CloudWatch agent
aggregates the data and sends it to the SDK Metrics service. Therefore, to receive metrics, you must add
the CloudWatch agent to your instance.
The following topics describe how to authorize, set up and configure, and define SDK Metrics in the AWS
SDK for Go.
Topics
• Authorize SDK Metrics to Collect and Send Metrics in the AWS SDK for Go (p. 9)
• Set up SDK Metrics in the AWS SDK for Go (p. 12)
• Definitions for SDK Metrics (p. 14)
Use the following Go code sample or the AWS Console to create an IAM Policy and Role for an
CloudWatch agent to access SDK Metrics in your environment.
Learn more about using SDK Metrics with AWS SDK for Go in Set up SDK Metrics in the AWS SDK for
Go (p. 12).
First, create a policy using CreatePolicy. Then create a role using CreateRole. Finally, attach the policy you
created to your new role with AttachRolePolicy.
package main
9
AWS SDK for Go Developer Guide
Authorize SDK Metrics
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"fmt"
"encoding/json"
"os"
)
/**
* Creates a new managed policy for your AWS account.
*
* This code assumes that you have already set up AWS credentials. See
* https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-
sdk.html#specifying-credentials
*/
func main() {
// Default name for policy, role policy.
RoleName := "AmazonCSM"
Description := "An instance role that has permission for AWS Systems Manager and SDK
Metric Monitoring."
AmazonCSMPolicy := map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{
"Effect": "Allow",
"Action": "sdkmetrics:*",
"Resource": "*",
},
{
"Effect": "Allow",
"Action": "ssm:GetParameter",
"Resource": "arn:aws:ssm:*:*:parameter/AmazonCSM*",
},
},
}
// Create policy
policyResponse, err := svc.CreatePolicy(&iam.CreatePolicyInput{
10
AWS SDK for Go Developer Guide
Authorize SDK Metrics
PolicyDocument: aws.String(string(policy)),
PolicyName: aws.String(RoleName + "policy"),
})
if err != nil {
fmt.Println("Got error creating policy:")
fmt.Println(err.Error())
os.Exit(1)
}
_, err = svc.CreateRole(input)
if err != nil {
fmt.Println("Got error creating role:")
fmt.Println(err.Error())
os.Exit(0)
}
11
AWS SDK for Go Developer Guide
Set Up SDK Metrics
To use SDK Metrics, run the latest version of the CloudWatch agent.
For details about IAM Permissions for SDK Metrics, see Authorize SDK Metrics to Collect and Send Metrics
in the AWS SDK for Go (p. 9).
1. Create an application with an AWS SDK for Go client to use an AWS service.
2. Host your project on an Amazon EC2 instance or in your local environment.
3. Install and use the latest version of the AWS SDK for Go.
4. Install and configure a CloudWatch agent on an Amazon EC2 instance or in your local environment.
5. Authorize SDK Metrics to collect and send metrics.
6. Enable SDK Metrics for the AWS SDK for Go (p. 12).
//default values
[
'enabled' => false,
'port' => 31000,
]
Enabling SDK Metrics is independent of configuring your credentials to use an AWS service.
12
AWS SDK for Go Developer Guide
Set Up SDK Metrics
You can enable SDK Metrics by setting environment variables or by using the AWS Shared config file.
export AWS_CSM_ENABLED=true
Other configuration settings are available, see update_cw_agent for details. For more information
about using shared files, see the environment variables information in Configuring the AWS SDK for
Go (p. 4).
Note
Enabling SDK Metrics does not configure your credentials to use an AWS service. To do that, see
Specifying Credentials (p. 5).
[default]
csm_enabled = true
[profile aws_csm]
csm_enabled = true
Other configuration settings are available, see update_cw_agent for details. For more information
about using shared files, see the environment variables information in Configuring the AWS SDK for
Go (p. 4).
Note
Enabling SDK Metrics does not configure your credentials to use an AWS service. To do that, see
Specifying Credentials (p. 5).
export AWS_CSM_ENABLED=true
export AWS_CSM_PORT=1234
13
AWS SDK for Go Developer Guide
SDK Metric Definitions
[default]
csm_enabled = false
csm_port = 1234
[profile aws_csm]
csm_enabled = false
csm_port = 1234
amazon-cloudwatch-agent-ctl -a stop;
amazon-cloudwatch-agent-ctl -a start;
export AWS_CSM_ENABLED=false
[default]
csm_enabled = false
[profile aws_csm]
csm_enabled = false
If you are using other CloudWatch features, restart CloudWatch with the following command.
amazon-cloudwatch-agent-ctl -a start;
14
AWS SDK for Go Developer Guide
Custom HTTP Client
impacting your application's performance, it is best to review that data during scheduled business
reviews.
ClientErrorCount Number of API calls that fail Except in certain cases related to
with client errors (4xx HTTP throttling (ex. when throttling
response codes). Examples: occurs due to a limit that needs
Throttling, Access denied, S3 to be increased) this metric
bucket does not exist, and can indicate something in your
Invalid parameter value. application that needs to be
fixed.
ConnectionErrorCount Number of API calls that fail Use this metric to determine
because of errors connecting to whether issues are specific
the service. These can be caused to your application or are
by network issues between caused by your infrastructure
the customer application and and/or network. High
AWS services including load ConnectionErrorCount could
balancers, DNS failures, transit also indicate short timeout
providers. In some cases, AWS values for API calls.
issues may result in this error.
ThrottleCount Number of API calls that fail due Use this metric to assess if
to throttling by AWS services. your application has reached
throttle limits, as well as
to determine the cause of
retries and application latency.
Consider distributing calls over a
window instead of batching your
calls.
ServerErrorCount Number of API calls that fail Determine cause of SDK retries
due to server errors (5xx HTTP or latency. This metric will
response codes) from AWS not always indicate that AWS
Services. These are typically services are at fault, as some
caused by AWS services. AWS teams classify latency as an
HTTP 503 response.
EndToEndLatency Total time for your application Determine how AWS API calls
to make a call using the AWS contribute to your application's
SDK, inclusive of retries. In other overall latency. Higher than
words, regardless of whether expected latency may be caused
it is successful after several by issues with network, firewall,
attempts, or as soon as a call or other configuration settings,
fails due to an unretriable error. or by latency that occurs as a
result of SDK retries.
15
AWS SDK for Go Developer Guide
Dialer.KeepAlive
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.
Dialer.KeepAlive
This setting represents the keep-alive period for an active network connection.
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
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
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
Transport.IdleConnTimeout
This setting represents the maximum amount of time to keep an idle network connection alive between
HTTP requests.
16
AWS SDK for Go Developer Guide
Transport.MaxIdleConns
See https://golang.org/pkg/net/http/#Transport.IdleConnTimeout
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
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
See https://golang.org/pkg/net/http/#Transport.MaxIdleConnsPerHost
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.
See https://golang.org/pkg/net/http/#Transport.ResponseHeaderTimeout
Transport.TLSHandshakeTimeout
This setting represents the maximum amount of time waiting for a TLS handshake to be completed.
Default is 10 seconds.
See https://golang.org/pkg/net/http/#Transport.TLSHandshakeTimeout
17
AWS SDK for Go Developer Guide
Create Import Statement
import (
"bytes"
"flag"
"fmt"
"net"
"net/http"
"os"
"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"
)
18
AWS SDK for Go Developer Guide
Using a Custom HTTP Client
return &http.Client{
Transport: tr,
}
}
sess := session.Must(session.NewSession(&aws.Config{
Region: regionPtr,
HTTPClient: 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,
}),
}))
client := 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 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.
defer resp.Body.Close()
19
AWS SDK for Go Developer Guide
Step 1: Set up Your AWS Account to Use AWS Cloud9
Follow these instructions to set up AWS Cloud9 with the AWS SDK for Go:
• Step 1: Set up Your AWS Account to Use AWS Cloud9 (p. 20)
• Step 2: Set up Your AWS Cloud9 Development Environment (p. 20)
• Step 3: Set up the AWS SDK for Go (p. 20)
• Step 4: Download Example Code (p. 21)
• Step 5: Run Example Code (p. 22)
To set up an IAM entity in your AWS account to access AWS Cloud9, and to sign in to the AWS Cloud9
console, see Team Setup for AWS Cloud9 in the AWS Cloud9 User Guide.
See Creating an Environment in AWS Cloud9 in the AWS Cloud9 User Guide for details.
Note
As you create your environment in the console for the first time, we recommend that you choose
the option to Create a new instance for environment (EC2). This option tells AWS Cloud9 to
create an environment, launch an Amazon EC2 instance, and then connect the new instance to
the new environment. This is the fastest way to begin using AWS Cloud9.
20
AWS SDK for Go Developer Guide
Step 4: Download Example Code
1. If the terminal isn't already open in the IDE, open it. On the menu bar in the IDE, choose Window, New
Terminal.
2. Set your GOPATH environment variable. To do this, add the following code to the end of your shell
profile file (for example, ~/.bashrc in Amazon Linux, assuming you chose the option to Create a
new instance for environment (EC2), earlier in this topic), and then save the file.
GOPATH=~/environment/go
export GOPATH
After you save the file, source the ~/.bashrc file to finish setting your GOPATH environment
variable. To do this, run the following command. (This command assumes you chose the option to
Create a new instance for environment (EC2), earlier in this topic.)
. ~/.bashrc
3. Run the following command to install the AWS SDK for Go.
go get -u github.com/aws/aws-sdk-go/...
If the IDE can't find Go, run the following commands, one at a time in this order, to install it. (These
commands assume you chose the option to Create a new instance for environment (EC2), earlier in this
topic. Also, these commands assume the latest stable version of Go at the time this topic was written; for
more information, see Downloads on The Go Programming Language website.)
After you install Go, add the path to the Go binary to your PATH environment variable. To do this, add
the following code to the end of your shell profile file (for example, ~/.bashrc in Amazon Linux,
assuming you chose the option to Create a new instance for environment (EC2), earlier in this topic),
and then save the file.
PATH=$PATH:/usr/local/go/bin
After you save the file, source the ~/.bashrc file so that the terminal can now find the Go binary you
just referenced. To do this, run the following command. (This command assumes you chose the option to
Create a new instance for environment (EC2), earlier in this topic.)
. ~/.bashrc
To do this, run the following command. This command downloads a copy of all of the code examples
used in the official AWS SDK documentation into your environment's root directory.
21
AWS SDK for Go Developer Guide
Step 5: Run Example Code
To find code examples for the AWS SDK for Go, use the Environment window to open the
ENVIRONMENT_NAME/aws-doc-sdk-examples/go/example_code directory, where
ENVIRONMENT_NAME is the name of your development environment.
To learn how to work with these and other code examples, see AWS SDK for Go Code
Examples (p. 36).
22
AWS SDK for Go Developer Guide
Concurrency
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.
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 (p. 23) 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.
23
AWS SDK for Go Developer Guide
Create Sessions with Option Overrides
The SDK provides a default configuration 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 in the AWS SDK for Go API Reference.
Use 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{})
// 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.
24
AWS SDK for Go Developer Guide
Shared Configuration Fields
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
See the session package's documentation 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 for more information on environment variable setup.
Copying a Session
You can use the 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:
25
AWS SDK for Go Developer Guide
Constructing a Service
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.
Constructing a Service
To construct a service client instance, use the NewSession() function. The following example creates an
Amazon S3 service client.
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 (p. 4).
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):
The following example shows how to tag the Amazon S3 bucket MyBucket with Cost Center tag with
the value 123456 and Stack tag with the value MyTestStack.
package main
import (
26
AWS SDK for Go Developer Guide
Tagging Service Resources
"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 MyBucket 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 := "MyBucket"
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
}
_, err = svc.PutBucketTagging(putInput)
if err != nil {
fmt.Println(err.Error())
return
}
27
AWS SDK for Go Developer Guide
Getting the HTTP Request and
Response with Each Service Call
numTags := len(result.TagSet)
if numTags > 0 {
fmt.Println("Found", numTags, "Tag(s):")
fmt.Println("")
Note that if a tag of the same name already exists, its value is overwriten by the new value.
The following example uses the DynamoDBListTables 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)
}
28
AWS SDK for Go Developer Guide
Service Operation Calls
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: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"]}
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 method:
29
AWS SDK for Go Developer Guide
Calling Operations with the Request Form
svc := s3.New(session.New())
svc.GetObject(&s3.GetObjectInput{
Bucket: aws.String("bucketName"),
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.
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 method signs the
request before sending it.
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&myStruct); err != nil {
// handle error
return
30
AWS SDK for Go Developer Guide
Concurrently Using Service Clients
In the following example, an Amazon S3 service client is used in multiple goroutines. The example
concurrently outputs all objects in bucket1, bucket2, and 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.
svc := s3.New(sess)
buckets := []string{"bucket1", "bucket2", "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)
}
31
AWS SDK for Go Developer Guide
Using Waiters
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, at most, three pages of
object keys from the ListObject operation. Each page consists of at least 10 keys, which is defined by
the MaxKeys field.
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.
32
AWS SDK for Go Developer Guide
Using Waiters
33
AWS SDK for Go Developer Guide
Handling Specific Service Error Codes
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.
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 {
34
AWS SDK for Go Developer Guide
Additional Error Information
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])
}
}
For more information, see the s3Manager.MultiUploadFailure interface in the AWS SDK for Go API
Reference.
35
AWS SDK for Go Developer Guide
SDK Request Examples
Topics
• AWS SDK for Go Request Examples (p. 36)
• AWS CloudTrail Examples Using the AWS SDK for Go (p. 37)
• Amazon CloudWatch Examples Using the AWS SDK for Go (p. 43)
• AWS CodeBuild Examples Using the AWS SDK for Go (p. 55)
• Amazon DynamoDB Examples Using the AWS SDK for Go (p. 57)
• Amazon EC2 Examples Using the AWS SDK for Go (p. 69)
• Amazon S3 Glacier Examples Using the AWS SDK for Go (p. 91)
• IAM Examples Using the AWS SDK for Go (p. 93)
• AWS Key Management Service Examples Using the AWS SDK for Go (p. 116)
• AWS Lambda Examples Using the AWS SDK for Go (p. 120)
• Amazon Polly Examples Using the AWS SDK for Go (p. 124)
• Amazon S3 Examples Using the AWS SDK for Go (p. 127)
• Amazon SES Examples Using the AWS SDK for Go (p. 163)
• Amazon SNS Examples Using the AWS SDK for Go (p. 169)
• Amazon SQS Examples Using the AWS SDK for Go (p. 173)
• Amazon WorkDocs Examples (p. 190)
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 SQSReceiveMessage.
err := req.Send()
if err != nil {
fmt.Println("Got error receiving message:")
36
AWS SDK for Go Developer Guide
Using API Field Setters with SDK Requests
fmt.Println(err.Error())
} else {
fmt.Println(resp)
}
svc.PutObject((&s3.PutObjectInput{}).
SetBucket("myBucket").
SetKey("myKey").
SetBody(strings.NewReader("object body")).
SetWebsiteRedirectLocation("https://example.com/something"),
)
You can also use this pattern with nested fields in API operation requests.
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 (p. 2) and Configuring the AWS SDK for Go (p. 4).
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Listing the CloudTrail Trails (p. 37)
• Creating a CloudTrail Trail (p. 38)
• Listing CloudTrail Trail Events (p. 41)
• Deleting a CloudTrail Trail (p. 42)
37
AWS SDK for Go Developer Guide
Creating a CloudTrail Trail
Create the file describe_trails.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudtrail"
"fmt"
"os"
)
Initialize the session that the SDK uses to load credentials from the shared credentials file .aws/
credentials in your home folder, and create a new service client.
Call DescribeTrails. If an error occurs, print the error and exit. If no error occurs, loop through the trails,
printing the name of each trail and the bucket.
Create the file create_trail.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
38
AWS SDK for Go Developer Guide
Creating a CloudTrail Trail
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/cloudtrail"
"github.com/aws/aws-sdk-go/service/sts"
"encoding/json"
"flag"
"fmt"
"os"
)
Get the names of the trail and bucket, and whether to attach the policy to the bucket. If either the trail
name or bucket name is missing, display an error message and exit.
flag.Parse()
Initialize the session that the SDK uses to load credentials from the shared credentials file .aws/
credentials in your home folder.
if addPolicy {
svc := sts.New(sess)
input := &sts.GetCallerIdentityInput{}
accountId := aws.StringValue(result.Account)
s3Policy := map[string]interface{}{
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{
"Sid": "AWSCloudTrailAclCheck20150319",
"Effect": "Allow",
"Principal": map[string]interface{}{
"Service": "cloudtrail.amazonaws.com",
39
AWS SDK for Go Developer Guide
Creating a CloudTrail Trail
},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::" + bucketName,
},
{
"Sid": "AWSCloudTrailWrite20150319",
"Effect": "Allow",
"Principal": map[string]interface{}{
"Service": "cloudtrail.amazonaws.com",
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::" + bucketName + "/AWSLogs/" + accountId + "/*",
"Condition": map[string]interface{}{
"StringEquals": map[string]interface{}{
"s3:x-amz-acl": "bucket-owner-full-control",
},
},
},
},
}
// Create S3 service
s3_svc := s3.New(sess)
Create the CloudTrail client, the input for CreateTrail, and call CreateTrail. If an error occurs, print the
error and exit. If no error occurs, print a success message.
svc := cloudtrail.New(sess)
input := &cloudtrail.CreateTrailInput{
Name: aws.String(trailName),
S3BucketName: aws.String(bucketName),
}
_, err = svc.CreateTrail(input)
if err != nil {
fmt.Println("Got error calling CreateTrail:")
fmt.Println(err.Error())
os.Exit(1)
}
40
AWS SDK for Go Developer Guide
Listing CloudTrail Trail Events
Create the file lookup_events.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudtrail"
"flag"
"fmt"
"os"
"time"
)
Get the name of the trail, and whether to display the event. If the trail name is missing, display an error
message and exit.
flag.Parse()
if trailName == "" {
fmt.Println("You must supply a trail name")
os.Exit(1)
}
Initialize the session that the SDK uses to load credentials from the shared credentials file .aws/
credentials in your home folder, and create a new service client.
Create the input for and call LookupEvents. If an error occurs, print the error and exit. If no error occurs,
loop through the events, printing information about each event. If the -s flag was specified, print the
CloudTrail event.
41
AWS SDK for Go Developer Guide
Deleting a CloudTrail Trail
fmt.Println(err.Error())
os.Exit(1)
}
fmt.Println("Resourcs:")
fmt.Println("")
}
Create the file delete_trail.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudtrail"
"flag"
"fmt"
"os"
)
Get the name of the trail. If the trail name is missing, display an error message and exit.
flag.Parse()
if trailName == "" {
fmt.Println("You must supply a trail name")
os.Exit(1)
}
42
AWS SDK for Go Developer Guide
Amazon CloudWatch Examples
Initialize the session that the SDK uses to load credentials from the shared credentials file .aws/
credentials in your home folder and create the client.
Call DeleteTrail with the trail name. If an error occurs, print the error and exit. If no error occurs, print a
success message.
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 (p. 2) and Configuring the AWS SDK for Go (p. 4).
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Describing CloudWatch Alarms (p. 43)
• Using Alarms and Alarm Actions in CloudWatch (p. 44)
• Getting Metrics from CloudWatch (p. 47)
• Sending Events to Amazon CloudWatch Events (p. 50)
• Getting Log Events from CloudWatch (p. 54)
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
43
AWS SDK for Go Developer Guide
Using Alarms and Alarm Actions in CloudWatch
Scenario
An alarm watches a single metric over a time period you specify. The alarm performs one or more actions
based on the value of the metric relative to a given threshold over a number of time periods.
In this example, Go code is used to describe alarms in CloudWatch. The code uses the AWS SDK for Go to
describe alarms by using this method of the AWS.CloudWatch client class:
• DescribeAlarms
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with CloudWatch alarms. To learn more, see Creating Amazon CloudWatch Alarms in
the Amazon CloudWatch User Guide.
Describe Alarms
Choose Copy to save the code locally.
Create the file describe_alarms.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"fmt"
"os"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := cloudwatch.New(sess)
44
AWS SDK for Go Developer Guide
Using Alarms and Alarm Actions in CloudWatch
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
You can use alarm actions to create alarms that automatically stop, terminate, reboot, or recover your
Amazon EC2 instances. You can use the stop or terminate actions when you no longer need an instance
to be running. You can use the reboot and recover actions to automatically reboot the instance.
In this example, Go code is used to define an alarm action in CloudWatch that triggers the reboot of an
Amazon EC2 instance. The code uses the AWS SDK for Go to manage instances by using these methods
of PutMetricAlarm type:
• PutMetricAlarm
• EnableAlarmActions
• DisableAlarmActions
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with CloudWatch alarm actions. To learn more, see Create Alarms to Stop, Terminate,
Reboot, or Recover an Instance in the Amazon CloudWatch User Guide.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"fmt"
"os"
)
if len(os.Args) != 4 {
fmt.Println("You must supply an instance name, value, and alarm name")
os.Exit(1)
}
instance := os.Args[1]
value := os.Args[2]
name := os.Args[3]
45
AWS SDK for Go Developer Guide
Using Alarms and Alarm Actions in CloudWatch
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Create a metric alarm that reboots an instance if its CPU utilization is greater than 70 percent.
_, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{
AlarmName: aws.String(name),
ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold),
EvaluationPeriods: aws.Int64(1),
MetricName: aws.String("CPUUtilization"),
Namespace: aws.String("AWS/EC2"),
Period: aws.Int64(60),
Statistic: aws.String(cloudwatch.StatisticAverage),
Threshold: aws.Float64(70.0),
ActionsEnabled: aws.Bool(true),
AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"),
Unit: aws.String(cloudwatch.StandardUnitSeconds),
// This is apart of the default workflow actions. This one will reboot the instance, if
the
// alarm is triggered.
AlarmActions: []*string{
aws.String(fmt.Sprintf("arn:aws:swf:us-east-1:%s:action/actions/
AWS_EC2.InstanceId.Reboot/1.0", instance)),
},
Dimensions: []*cloudwatch.Dimension{
{
Name: aws.String("InstanceId"),
Value: aws.String(value),
},
},
})
Call EnableAlarmActions with the new alarm for the instance, and display a message.
import (
46
AWS SDK for Go Developer Guide
Getting Metrics from CloudWatch
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"fmt"
"os"
main() {
if len(os.Args) != 2 {
fmt.Println("You must supply an alarm name")
os.Exit(1)
}
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch client.
Call DisableAlarmActions to disable the actions for this alarm and display a message.
• Listing metrics
• Submitting custom metrics
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
Metrics are data about the performance of your systems. You can enable detailed monitoring of some
resources, such as your Amazon EC2 instances, or your own application metrics.
In this example, Go code is used to get metrics from CloudWatch and to send events to CloudWatch
Events. The code uses the AWS SDK for Go to get metrics from CloudWatch by using these methods of
the CloudWatch type:
47
AWS SDK for Go Developer Guide
Getting Metrics from CloudWatch
• ListMetrics
• PutMetricData
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with CloudWatch metrics. To learn more, see Using Amazon CloudWatch Metrics in the
Amazon CloudWatch User Guide.
List Metrics
Choose Copy to save the code locally.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"fmt"
"os"
)
Get the metric name, namespace, and dimension name from the command line.
if len(os.Args) != 4 {
fmt.Println("You must supply a metric name, namespace, and dimension name")
os.Exit(1)
}
metric := os.Args[1]
namespace := os.Args[2]
dimension := os.Args[3]
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Call ListMetrics, supplying the metric name, namespace, and dimension name. Print the metrics
returned in the result.
48
AWS SDK for Go Developer Guide
Getting Metrics from CloudWatch
},
},
})
fmt.Println("Metrics", result.Metrics)
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Call PutMetricData with the the custom namespace "Site/Traffic". The namespace has two custom
dimensions: "SiteName" and "PageURL". "SiteName" has the value "example.com", the "UniqueVisitors"
value 5885 and the "UniqueVisits" value 8628. "PageURL" has the value "my-page.html", and a
"PageViews" value 18057.
_, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{
Namespace: aws.String("Site/Traffic"),
MetricData: []*cloudwatch.MetricDatum{
&cloudwatch.MetricDatum{
MetricName: aws.String("UniqueVisitors"),
Unit: aws.String("Count"),
Value: aws.Float64(5885.0),
Dimensions: []*cloudwatch.Dimension{
&cloudwatch.Dimension{
Name: aws.String("SiteName"),
Value: aws.String("example.com"),
},
},
},
&cloudwatch.MetricDatum{
MetricName: aws.String("UniqueVisits"),
Unit: aws.String("Count"),
Value: aws.Float64(8628.0),
Dimensions: []*cloudwatch.Dimension{
&cloudwatch.Dimension{
Name: aws.String("SiteName"),
Value: aws.String("example.com"),
49
AWS SDK for Go Developer Guide
Sending Events to Amazon CloudWatch Events
},
},
},
&cloudwatch.MetricDatum{
MetricName: aws.String("PageViews"),
Unit: aws.String("Count"),
Value: aws.Float64(18057.0),
Dimensions: []*cloudwatch.Dimension{
&cloudwatch.Dimension{
Name: aws.String("PageURL"),
Value: aws.String("my-page.html"),
},
},
},
},
})
If there are any errors, print them out, otherwise list some information about the custom metrics.
if err != nil {
fmt.Println("Error adding metrics:", err.Error())
return
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
CloudWatch Events delivers a near real-time stream of system events that describe changes in AWS
resources to any of various targets. Using simple rules, you can match events and route them to one or
more target functions or streams.
50
AWS SDK for Go Developer Guide
Sending Events to Amazon CloudWatch Events
In these examples, Go code is used to send events to CloudWatch Events. The code uses the AWS SDK for
Go to manage instances by using these methods of the CloudWatchEvents type:
• PutRule
• PutTargets
• PutEvents
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with CloudWatch Events. To learn more, see Adding Events with PutEvents in the
Amazon CloudWatch Events User Guide.
1. Create a Lambda function using the hello-world blueprint to serve as the target for events. To learn
how, see Step 1: Create an AWS Lambda function in the CloudWatch Events User Guide.
2. Create an IAM role whose policy grants permission to CloudWatch Events and that includes
events.amazonaws.com as a trusted entity. For more information about creating an IAM role, see
Creating a Role to Delegate Permissions to an AWS Service in the IAM User Guide.
Use the following role policy when creating the IAM role.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudWatchEventsFullAccess",
"Effect": "Allow",
"Action": "events:*",
"Resource": "*"
},
{
"Sid": "IAMPassRoleForCloudWatchEvents",
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets"
}
]
}
Use the following trust relationship when creating the IAM role.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
51
AWS SDK for Go Developer Guide
Sending Events to Amazon CloudWatch Events
Create the file events_schedule_rule.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch Events client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Call PutRule, supplying a name, DEMO_EVENT, ARN of the IAM role you created, IAM_ROLE_ARN, and an
expression defining the schedule. Finally, display the ARN of the rule.
Create the file events_put_targets.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a new
CloudWatch Events client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
52
AWS SDK for Go Developer Guide
Sending Events to Amazon CloudWatch Events
SharedConfigState: session.SharedConfigEnable,
}))
Call PutTargets, supplying a name for the rule, DEMO_EVENT. For the target, specify the
ARN of the Lambda function you created, LAMBDA_FUNCTION_ARN, and the ID of the rule,
myCloudWatchEventsTarget. Print any errors, or a success message with any targets that failed.
Send Events
Choose Copy to save the code locally.
Create the file events_put_events.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create a
CloudWatch Events client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Call PutEvents, supplying key-name value pairs in the Details field, and specifying the ARN of the
Lambda function you created, RESOURCE_ARN. See PutEventsRequestEntry for a description of the
fields. Finally, display the ingested events.
53
AWS SDK for Go Developer Guide
Getting Log Events from CloudWatch
Source: aws.String("com.company.myapp"),
},
},
})
fmt.Println("Ingested events:", result.Entries)
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/cloudwatchlogs"
"fmt"
"os"
)
func main() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := cloudwatchlogs.New(sess)
gotToken := ""
nextToken := ""
if gotToken == nextToken {
break
}
54
AWS SDK for Go Developer Guide
AWS CodeBuild Examples
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Getting Information about All AWS CodeBuild Projects (p. 55)
• Building an AWS CodeBuild Project (p. 56)
• Listing Your AWS CodeBuild Project Builds (p. 56)
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/codebuild"
"fmt"
"os"
)
if err != nil {
fmt.Println("Got error listing projects: ", err)
os.Exit(1)
}
55
AWS SDK for Go Developer Guide
Building an AWS CodeBuild Project
}
}
Choose Copy to save the code locally. See the complete example on GitHub.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/codebuild"
"fmt"
"os"
)
project := os.Args[1]
Choose Copy to save the code locally. See the complete example on GitHub.
package main
import (
56
AWS SDK for Go Developer Guide
Amazon DynamoDB Examples
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/codebuild"
"fmt"
"os"
)
// Lists the CodeBuild builds for all projects in the region configured in the shared
config
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Got error listing builds: ", err)
os.Exit(1)
}
if err != nil {
fmt.Println("Got error getting builds: ", err)
os.Exit(1)
}
Choose Copy to save the code locally. See the complete example on GitHub.
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 repository
on GitHub.
57
AWS SDK for Go Developer Guide
Listing all Amazon DynamoDB Tables
Topics
• Listing all Amazon DynamoDB Tables (p. 58)
• Creating an Amazon DynamoDB Table (p. 59)
• Creating an Amazon DynamoDB Table Item (p. 60)
• Creating Amazon DynamoDB Table Items from a JSON File (p. 62)
• Reading an Amazon DynamoDB Table Item (p. 63)
• Getting Amazon DynamoDB Table Items Using Expression Builder (p. 65)
• Updating an Amazon DynamoDB Table Item (p. 67)
• Deleting an Amazon DynamoDB Table Item (p. 68)
Create the file DynamoDBListTables.go. Add the following statements to import the Go and AWS SDK for
Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config and create a new DynamoDB
service client.
Call ListTables. If an error occurs, print the error and exit. If no error occurs, loop through the tabless,
printing the name of each table.
fmt.Printf("Tables:\n")
for {
// Get the list of tables
result, err := svc.ListTables(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
58
AWS SDK for Go Developer Guide
Creating an Amazon DynamoDB Table
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
// assign the last read tablename as the start for our next call to the ListTables
function
// the maximum number of table names returned in a call is 100 (default), which
requires us to make
// multiple calls to the ListTables function to retrieve all table names
input.ExclusiveStartTableName = result.LastEvaluatedTableName
if result.LastEvaluatedTableName == nil {
break
}
}
Create the file DynamoDBCreateTable.go. Add the following statements to import the Go and AWS SDK
for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"fmt"
"os"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config, and create the DynamoDB client.
59
AWS SDK for Go Developer Guide
Creating an Amazon DynamoDB Table Item
Call CreateTable. If an error occurs, print the error and exit. If no error occurs, print an message that the
table was created.
input := &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("Year"),
AttributeType: aws.String("N"),
},
{
AttributeName: aws.String("Title"),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("Year"),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String("Title"),
KeyType: aws.String("RANGE"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(10),
WriteCapacityUnits: aws.Int64(10),
},
TableName: aws.String(tableName),
}
_, err := svc.CreateTable(input)
if err != nil {
fmt.Println("Got error calling CreateTable:")
fmt.Println(err.Error())
os.Exit(1)
}
Create the file DynamoDBCreateItem.go. Add the following statements to import the Go and AWS SDK
for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"fmt"
"os"
"strconv"
60
AWS SDK for Go Developer Guide
Creating an Amazon DynamoDB Table Item
Create the data structure we use to containing the information about the table item.
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config, and create the DynamoDB client.
Create a struct with the movie data and marshall that data into a map of AttributeValue objects.
item := Item{
Year: 2015,
Title: "The Big New Movie",
Plot: "Nothing happens at all.",
Rating: 0.0,
}
Create the input for PutItem and call it. If an error occurs, print the error and exit. If no error occurs, print
an message that the item was added to the table.
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String(tableName),
}
_, err = svc.PutItem(input)
if err != nil {
fmt.Println("Got error calling PutItem:")
fmt.Println(err.Error())
os.Exit(1)
}
61
AWS SDK for Go Developer Guide
Creating Amazon DynamoDB Table Items from a JSON File
year := strconv.Itoa(movieYear)
fmt.Println("Successfully added '" + movieName + "' (" + year + ") to table " + tableName)
Create the file DynamoDBLoadItems.go. Add the following statements to import the Go and AWS SDK for
Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
)
Create the data structure we use to contain the information about the table item.
Create a function to get the table items from the JSON file.
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config and create a new DynamoDB
service client.
62
AWS SDK for Go Developer Guide
Reading an Amazon DynamoDB Table Item
Call getItems to get the items. Loop through each item, marshall that data into a map of AttributeValue
objects, add the item to the Movies table, and print out the title and year of the movie added to the
table.
_, err = svc.PutItem(input)
if err != nil {
fmt.Println("Got error calling PutItem:")
fmt.Println(err.Error())
os.Exit(1)
}
year := strconv.Itoa(item.Year)
fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " +
tableName)
Create the file DynamoDBReadItem.go. Add the following statements to import the Go and AWS SDK for
Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"fmt"
63
AWS SDK for Go Developer Guide
Reading an Amazon DynamoDB Table Item
Create the data structure we use to contain the information about the table item.
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config and create a new DynamoDB
service client.
Call GetItem to get the item from the table. If we encounter an error, print the error message. Otherwise,
display information about the item.
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"
Unmarshall the return value and if the title is not empty, indicating we got the item, display the year,
title, plot, and rating.
item := Item{}
if item.Title == "" {
64
AWS SDK for Go Developer Guide
Getting Amazon DynamoDB Table
Items Using Expression Builder
fmt.Println("Found item:")
fmt.Println("Year: ", item.Year)
fmt.Println("Title: ", item.Title)
fmt.Println("Plot: ", item.Plot)
fmt.Println("Rating:", item.Rating)
The example uses the Expression Builder package released in version 1.11.0 of the AWS SDK for Go in
September 2017.
Create the file DynamoDBScanItem.go. Add the following statements to import the Go and AWS SDK for
Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
"fmt"
"os"
)
Create the data structure we use to contain the information about the table item.
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config and create a new DynamoDB
service client.
65
AWS SDK for Go Developer Guide
Getting Amazon DynamoDB Table
Items Using Expression Builder
Create variables for the minimum rating and year for the table items to retrieve.
tableName := "Movies"
minRating := 4.0
year := 2013
Create the expression defining the year for which we filter the table items to retrieve, and the projection
so we get the title, year, and rating for each retrieved item. Then build the expression.
// Or we could get by ratings and pull out those with the right year later
// filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating))
Create the inputs for and call Scan to retrieve the items from the table (the movies made in 2013).
Loop through the movies from 2013 and display the title and rating for those where the rating is greater
than 4.0
numItems := 0
if err != nil {
fmt.Println("Got error unmarshalling:")
fmt.Println(err.Error())
os.Exit(1)
}
66
AWS SDK for Go Developer Guide
Updating an Amazon DynamoDB Table Item
Create the file DynamoDBUpdateItem.go. Add the following statements to import the Go and AWS SDK
for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config and create a new DynamoDB
service client.
Call UpdateItem to add the item to the table. If we encounter an error, print the error message.
Otherwise, display a message that the item was updated.
input := &dynamodb.UpdateItemInput{
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":r": {
N: aws.String(movieRating),
67
AWS SDK for Go Developer Guide
Deleting an Amazon DynamoDB Table Item
},
},
TableName: aws.String(tableName),
Key: map[string]*dynamodb.AttributeValue{
"Year": {
N: aws.String(movieYear),
},
"Title": {
S: aws.String(movieName),
},
},
ReturnValues: aws.String("UPDATED_NEW"),
UpdateExpression: aws.String("set Rating = :r"),
}
_, err := svc.UpdateItem(input)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Successfully updated '" + movieName + "' (" + movieYear + ") rating to " +
movieRating)
Create the file DynamoDBUpdateItem.go. Add the following statements to import the Go and AWS SDK
for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"fmt"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials and region from the shared configuration file ~/.aws/config and create a new DynamoDB
service client.
Call DeleteItem to delete the item from the table. If we encounter an error, print the error message.
Otherwise, display a message that the item was deleted.
tableName := "Movies"
movieName := "The Big New Movie"
68
AWS SDK for Go Developer Guide
Amazon EC2 Examples
movieYear := "2015"
input := &dynamodb.DeleteItemInput{
Key: map[string]*dynamodb.AttributeValue{
"Year": {
N: aws.String(movieYear),
},
"Title": {
S: aws.String(movieName),
},
},
TableName: aws.String(tableName),
}
_, err := svc.DeleteItem(input)
if err != nil {
fmt.Println("Got error calling DeleteItem")
fmt.Println(err.Error())
return
}
fmt.Println("Deleted '" + movieName + "' (" + movieYear + ") from table " + tableName)
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Creating Amazon EC2 Instances with Tags or without Block Devices (p. 69)
• Managing Amazon EC2 Instances (p. 72)
• Working with Amazon EC2 Key Pairs (p. 77)
• Using Regions and Availability Zones with Amazon EC2 (p. 80)
• Working with Security Groups in Amazon EC2 (p. 82)
• Using Elastic IP Addresses in Amazon EC2 (p. 87)
• Create an Amazon EC2 instance with tags or set up an instance without a block device
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
69
AWS SDK for Go Developer Guide
Creating Amazon EC2 Instances
with Tags or without Block Devices
Scenarios
In these examples, you use a series of Go routines to create Amazon EC2 instances with tags or set up an
instance without a block device.
The routines use the AWS SDK for Go to perform these tasks by using these methods of the EC2 type:
• BlockDeviceMapping
• RunInstances
• CreateTags
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"fmt"
"log"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Could not create instance", err)
return
}
70
AWS SDK for Go Developer Guide
Creating Amazon EC2 Instances
with Tags or without Block Devices
Resources: []*string{runResult.Instances[0].InstanceId},
Tags: []*ec2.Tag{
{
Key: aws.String("Name"),
Value: aws.String("MyFirstInstance"),
},
},
})
if errtag != nil {
log.Println("Could not create tags for instance",
runResult.Instances[0].InstanceId, errtag)
return
}
The NoDevice parameter is compatible only with DeviceName, not with any other field in
BlockDeviceMapping. The request will fail if other parameters are present.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"fmt"
)
func main() {
// Load session from shared config
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
opts := &ec2.CreateImageInput{
Description: aws.String("image description"),
InstanceId: aws.String("i-abcdef12"),
Name: aws.String("image name"),
BlockDeviceMappings: []*ec2.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/sda1"),
NoDevice: aws.String(""),
},
{
DeviceName: aws.String("/dev/sdb"),
NoDevice: aws.String(""),
},
{
71
AWS SDK for Go Developer Guide
Managing Amazon EC2 Instances
DeviceName: aws.String("/dev/sdc"),
NoDevice: aws.String(""),
},
},
}
resp, err := svc.CreateImage(opts)
if err != nil {
fmt.Println(err)
return
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
In these examples, you use a series of Go routines to perform several basic instance management
operations.
The routines use the AWS SDK for Go to perform the operations by using these methods of the Amazon
EC2 client class:
• DescribeInstances
• MonitorInstances
• UnmonitorInstances
• StartInstances
• StopInstances
• RebootInstances
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with the lifecycle of Amazon EC2 instances. To learn more, see Instance Lifecycle in the
Amazon EC2 User Guide for Linux Instances.
72
AWS SDK for Go Developer Guide
Managing Amazon EC2 Instances
The Amazon EC2 service has an operation for describing instances, DescribeInstances.
package main
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"fmt"
)
Use the following code to create a session and Amazon EC2 client.
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Success", result)
}
}
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
// Load session from shared config
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
73
AWS SDK for Go Developer Guide
Managing Amazon EC2 Instances
}))
Based on the value of a command-line argument (ON or OFF), call either the MonitorInstances
method of the Amazon EC2 service object to begin detailed monitoring of the specified instances, or the
UnmonitorInstances method. Before you try to change the monitoring of these instances, use the
DryRun parameter to test whether you have permission to change instance monitoring.
if os.Args[1] == "ON" {
input := &ec2.MonitorInstancesInput{
InstanceIds: []*string{
aws.String(os.Args[2]),
},
DryRun: aws.Bool(true),
}
result, err := svc.MonitorInstances(input)
awsErr, ok := err.(awserr.Error)
74
AWS SDK for Go Developer Guide
Managing Amazon EC2 Instances
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
To access Amazon EC2, create an EC2 client. The user will pass in a state value of START or STOP and the
instance ID.
func main() {
// Load session from shared config
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Based on the value of a command-line argument (START or STOP), call either the StartInstances
method of the Amazon EC2 service object to start the specified instances, or the StopInstances
method to stop them. Before you try to start or stop the selected instances, use the DryRun parameter
to test whether you have permission to start or stop them.
if os.Args[1] == "START" {
input := &ec2.StartInstancesInput{
InstanceIds: []*string{
aws.String(os.Args[2]),
},
DryRun: aws.Bool(true),
}
result, err := svc.StartInstances(input)
awsErr, ok := err.(awserr.Error)
75
AWS SDK for Go Developer Guide
Managing Amazon EC2 Instances
Reboot Instances
Create a new Go file named reboot_instances.go.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
To access Amazon EC2, create an EC2 client. The user will pass in a state value of START or STOP and the
instance ID.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Based on the value of a command-line argument (START or STOP), call either the StartInstances
method of the Amazon EC2 service object to start the specified instances, or the StopInstances
method to stop them. Before you try to reboot the selected instances, use the DryRun parameter to test
whether the instance exists and that you have permission to reboot it.
input := &ec2.RebootInstancesInput{
InstanceIds: []*string{
aws.String(os.Args[1]),
},
DryRun: aws.Bool(true),
}
result, err := svc.RebootInstances(input)
awsErr, ok := err.(awserr.Error)
If the error code is DryRunOperation, it means that you do have the permissions you need to reboot
the instance.
76
AWS SDK for Go Developer Guide
Working with Amazon EC2 Key Pairs
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
Amazon EC2 uses public–key cryptography to encrypt and decrypt login information. Public–key
cryptography uses a public key to encrypt data, then the recipient uses the private key to decrypt the
data. The public and private keys are known as a key pair.
The routines use the AWS SDK for Go to perform these tasks by using these methods of the EC2 type:
• CreateKeyPair
• DeleteKeyPair
• DescribeKeyPairs
Prerequisites
• You have set up (p. 2) and configured (p. 4) the SDK.
• You are familiar with Amazon EC2 key pairs. To learn more, see Amazon EC2 Key Pairs in the Amazon
EC2 User Guide for Linux Instances.
package main
77
AWS SDK for Go Developer Guide
Working with Amazon EC2 Key Pairs
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"fmt"
"os"
Use the following code to create a session and Amazon EC2 client.
// go run ec2_describe_keypairs.go
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call DescribeKeyPairs to get a list of key pairs and print them out.
fmt.Println("Key Pairs:")
for _, pair := range result.KeyPairs {
fmt.Printf("%s: %s\n", *pair.KeyName, *pair.KeyFingerprint)
}
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
78
AWS SDK for Go Developer Guide
Working with Amazon EC2 Key Pairs
Get the key pair name passed in to the code and, to access Amazon EC2, create an EC2 client.
func main() {
if len(os.Args) != 2 {
exitErrorf("pair name required\nUsage: %s key_pair_name",
filepath.Base(os.Args[0]))
}
pairName := os.Args[1]
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
79
AWS SDK for Go Developer Guide
Using Regions and Availability Zones with Amazon EC2
Get the key pair name passed in to the code and, to access Amazon EC2, create an EC2 client.
func main() {
if len(os.Args) != 2 {
exitErrorf("pair name required\nUsage: %s key_pair_name",
filepath.Base(os.Args[0]))
}
pairName := os.Args[1]
_, err = svc.DeleteKeyPair(&ec2.DeleteKeyPairInput{
KeyName: aws.String(pairName),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() ==
"InvalidKeyPair.Duplicate" {
exitErrorf("Key pair %q does not exist.", pairName)
}
exitErrorf("Unable to delete key pair: %s, %v.", pairName, err)
}
An Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or more
instances. You add rules to each security group to allow traffic to or from its associated instances. You
can modify the rules for a security group at any time; the new rules are automatically applied to all
instances that are associated with the security group.
The code in this example uses the AWS SDK for Go to perform these tasks by using these methods of the
Amazon EC2 client class:
• DescribeSecurityGroups
• AuthorizeSecurityGroupIngress
• CreateSecurityGroup
80
AWS SDK for Go Developer Guide
Using Regions and Availability Zones with Amazon EC2
• DescribeVpcs
• DeleteSecurityGroup
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
Amazon EC2 is hosted in multiple locations worldwide. These locations are composed of AWS Regions
and Availability Zones. Each region is a separate geographic area with multiple, isolated locations known
as Availability Zones. Amazon EC2 provides the ability to place instances and data in these multiple
locations.
In this example, you use Go code to retrieve details about regions and Availability Zones. The code uses
the AWS SDK for Go tomanage instances by using the following methods of the Amazon EC2 client class:
• DescribeAvailabilityZones
• DescribeRegions
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with AWS Regions and Availability Zones. To learn more, see Regions and Availability
Zones in the Amazon EC2 User Guide for Linux Instances or Regions and Availability Zones in the
Amazon EC2 User Guide for Windows Instances.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
In the main function, create a session with credentials from the shared credentials file, ~/.aws/
credentials, and create a new EC2 client.
func main() {
// Load session from shared config
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
81
AWS SDK for Go Developer Guide
Working with Security Groups in Amazon EC2
svc := ec2.New(sess)
Print out the list of regions that work with Amazon EC2 that are returned by calling DescribeRegions.
Add a call that retrieves Availability Zones only for the region of the EC2 service object.
fmt.Println("Success", resultAvalZones.AvailabilityZones)
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
An Amazon EC2 security group acts as a virtual firewall that controls the traffic for one or more
instances. You add rules to each security group to allow traffic to or from its associated instances. You
can modify the rules for a security group at any time; the new rules are automatically applied to all
instances that are associated with the security group.
The code in this example uses the AWS SDK for Go to perform these tasks by using these methods of the
Amazon EC2 client class:
• DescribeSecurityGroups
• AuthorizeSecurityGroupIngress
• CreateSecurityGroup
• DescribeVpcs
• DeleteSecurityGroup
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
82
AWS SDK for Go Developer Guide
Working with Security Groups in Amazon EC2
• You are familiar with Amazon EC2 security groups. To learn more, see Amazon EC2 Amazon Security
Groups for Linux Instances in the Amazon EC2 User Guide for Linux Instances or Amazon EC2 Amazon
Security Groups for Windows Instances in the Amazon EC2 User Guide for Windows Instances.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
In the main function, get the security group ID that is passed in.
func main() {
if len(os.Args) < 2 {
exitErrorf("Security Group ID required\nUsage: %s group_id ...",
filepath.Base(os.Args[0]))
}
groupIds := os.Args[1:]
Obtain and print out the security group descriptions. You will explicity check for errors caused by an
invalid group ID.
83
AWS SDK for Go Developer Guide
Working with Security Groups in Amazon EC2
}
exitErrorf("Unable to get descriptions for security groups, %v", err)
}
fmt.Println("Security Group:")
for _, group := range result.SecurityGroups {
fmt.Println(group)
}
This example creates a new security group with the given name and description for access to open ports
80 and 22. If a VPC ID is not provided, it associates the security group with the first VPC in the account.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"flag"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
Get the parameters (name, description, and optional ID of the VPC) that are passed in to the routine.
func main() {
var name, desc, vpcID string
flag.StringVar(&name, "n", "", "Group Name")
flag.StringVar(&desc, "d", "", "Group Description")
flag.StringVar(&vpcID, "vpc", "", "(Optional) VPC ID to associate security group with")
flag.Parse()
if len(name) == 0 || len(desc) == 0 {
flag.PrintDefaults()
exitErrorf("Group name and description require")
}
Create a session.
84
AWS SDK for Go Developer Guide
Working with Security Groups in Amazon EC2
If the VPC ID was not provided, you have to retrieve the first one in the account.
if len(vpcID) == 0 {
// Get a list of VPCs so we can associate the group with the first VPC.
result, err := svc.DescribeVpcs(nil)
if err != nil {
exitErrorf("Unable to describe VPCs, %v", err)
}
if len(result.Vpcs) == 0 {
exitErrorf("No VPCs found to associate security group with.")
}
vpcID = aws.StringValue(result.Vpcs[0].VpcId)
}
Then create the security group with the VPC ID, name, and description.
_, err = svc.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{
GroupName: aws.String(name),
IpPermissions: []*ec2.IpPermission{
(&ec2.IpPermission{}).
SetIpProtocol("tcp").
SetFromPort(80).
SetToPort(80).
SetIpRanges([]*ec2.IpRange{
{CidrIp: aws.String("0.0.0.0/0")},
}),
(&ec2.IpPermission{}).
SetIpProtocol("tcp").
SetFromPort(22).
SetToPort(22).
SetIpRanges([]*ec2.IpRange{
(&ec2.IpRange{}).
SetCidrIp("0.0.0.0/0"),
}),
},
})
if err != nil {
85
AWS SDK for Go Developer Guide
Working with Security Groups in Amazon EC2
This example deletes a security group with the given group ID.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
if len(os.Args) != 2 {
exitErrorf("Security Group ID required\nUsage: %s group_id",
filepath.Base(os.Args[0]))
}
groupID := os.Args[1]
Create a session.
Then delete the security group with the group ID that is passed in.
_, err = svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{
GroupId: aws.String(groupID),
86
AWS SDK for Go Developer Guide
Using Elastic IP Addresses in Amazon EC2
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "InvalidGroupId.Malformed":
fallthrough
case "InvalidGroup.NotFound":
exitErrorf("%s.", aerr.Message())
}
}
exitErrorf("Unable to get descriptions for security groups, %v.", err)
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
An Elastic IP address is a static IP address designed for dynamic cloud computing that is associated with
your AWS account. It is a public IP address, reachable from the Internet. If your instance doesn't have a
public IP address, you can associate an Elastic IP address with the instance to enable communication with
the Internet.
In this example, you use a series of Go routines to perform several Amazon EC2 operations involving
Elastic IP addresses. The routines use the AWS SDK for Go to manage Elastic IP addresses by using these
methods of the Amazon EC2 client class:
• DescribeAddresses
• AllocateAddress
• AssociateAddress
• ReleaseAddress
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
87
AWS SDK for Go Developer Guide
Using Elastic IP Addresses in Amazon EC2
• You are familiar with Elastic IP addresses in Amazon EC2. To learn more, see Elastic IP Addresses in the
Amazon EC2 User Guide for Linux Instances or Elastic IP Addresses in the Amazon EC2 User Guide for
Windows Instances.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Make the API request to EC2 filtering for the addresses in the account's VPC.
88
AWS SDK for Go Developer Guide
Using Elastic IP Addresses in Amazon EC2
The fmtAddress and exitErrorf functions are utility functions used in the example.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
This routine attempts to allocate a VPC Elastic IP address for the current region. The IP address requires
and will be associated with the instance ID that is passed in.
func main() {
if len(os.Args) != 2 {
exitErrorf("instance ID required\nUsage: %s instance_id",
filepath.Base(os.Args[0]))
}
instanceID := os.Args[1]
You will need to initialize a session that the SDK will use to load credentials from the shared credentials
file, ~/.aws/credentials, and create a new Amazon S3 service client.
89
AWS SDK for Go Developer Guide
Using Elastic IP Addresses in Amazon EC2
Domain: aws.String("vpc"),
})
if err != nil {
exitErrorf("Unable to allocate IP address, %v", err)
}
Call AssociateAddress to associate the new Elastic IP address with an existing Amazon EC2 instance, and
print out the results.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
The routine requires that the user pass in the allocation ID of the Elastic IP address.
func main() {
if len(os.Args) != 2 {
90
AWS SDK for Go Developer Guide
Amazon Glacier Examples
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials, and create a new EC2 service client.
_, err = svc.ReleaseAddress(&ec2.ReleaseAddressInput{
AllocationId: aws.String(allocationID),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() ==
"InvalidAllocationID.NotFound" {
exitErrorf("Allocation ID %s does not exist", allocationID)
}
exitErrorf("Unable to release IP address for allocation %s, %v",
allocationID, err)
}
91
AWS SDK for Go Developer Guide
The Scenario
imported all required packages and set your credentials and region). For more information, see Getting
Started with the AWS SDK for Go (p. 2) and Configuring the AWS SDK for Go (p. 4).
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
The Scenario
Amazon S3 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
• UploadArchive
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with the Amazon S3 Glacier data model. To learn more, see Amazon Glacier Data
Model in the Amazon S3 Glacier Developer Guide.
Create a Vault
The following example uses the Amazon S3 GlacierCreateVault operation to create a vault named
YOUR_VAULT_NAME.
rt (
"log"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/glacier"
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,
}))
// 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
92
AWS SDK for Go Developer Guide
Upload an Archive
Upload an Archive
The following example assumes you have a vault named YOUR_VAULT_NAME. It uses the Amazon S3
GlacierUploadArchive 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.
rt (
"bytes"
"log"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/glacier"
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,
}))
// start snippet
vaultName := "YOUR_VAULT_NAME"
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 (p. 2) and Configuring the AWS SDK for Go (p. 4).
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
93
AWS SDK for Go Developer Guide
Managing IAM Users
Scenario
In this example, you use a series of Go routines to manage users in IAM. The routines use the AWS SDK
for Go IAM client methods that follow:
• CreateUser
• ListUsers
• UpdateUser
• GetUser
• DeleteUser
• GetAccountAuthorizationDetails
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with IAM users. To learn more, see IAM Users in the IAM User Guide.
Create a new Go file named iam_createuser.go. You must import the relevant Go and AWS SDK for
Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
The code takes the new user name as an argument, and then calls GetUser with the user name.
94
AWS SDK for Go Developer Guide
Managing IAM Users
_, err = svc.GetUser(&iam.GetUserInput{
UserName: &os.Args[1],
If you receive a NoSuchEntity error, call CreateUser because the user doesn't exist.
if err != nil {
fmt.Println("CreateUser Error", err)
return
}
fmt.Println("Success", result)
} else {
fmt.Println("GetUser Error", err)
}
Create a new Go file named iam_listusers.go. You must import the relevant Go and AWS SDK for Go
packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
95
AWS SDK for Go Developer Guide
Managing IAM Users
if err != nil {
fmt.Println("Error", err)
return
}
Create a new Go file named iam_updateuser.go. You must import the relevant Go and|sdk-go|
packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
Call UpdateUser, passing in the original user name and the new name, and print the results.
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", result)
96
AWS SDK for Go Developer Guide
Managing IAM Users
Create a new Go file named iam_deleteuser.go. You must import the relevant Go and AWS SDK for
Go packages by adding the following lines.
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
Call DeleteUser, passing in the user name, and print the results. If the user doesn't exist, display an
error.
_, err = svc.DeleteUser(&iam.DeleteUserInput{
UserName: &os.Args[1],
})
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"fmt"
"os"
)
Create a method to determine whether a user has a policy that has administrator privileges.
97
AWS SDK for Go Developer Guide
Managing IAM Users
return false
}
Create a method to determine whether a user has an attached policy that has administrator privileges.
return false
}
Create a method that determines whether a group has a policy that has adminstrator privileges.
return false
}
Create a method that determines whether a group has an attached policy that has administrator
privileges.
98
AWS SDK for Go Developer Guide
Managing IAM Users
return false
}
Create a method that determines whether any group to which the user belongs has administrator
privileges.
if groupPolicyHasAdmin {
return true
}
if attachedGroupPolicyHasAdmin {
return true
}
}
return false
}
return false
}
Create a main method with an IAM client in us-west-2. Create variables to keep track of how many
users we have and how many of those have adminstrator privileges.
func main() {
sess, err := session.NewSession()
if err != nil {
fmt.Println("Got error creating new session")
fmt.Println(err.Error())
99
AWS SDK for Go Developer Guide
Managing IAM Users
os.Exit(1)
}
numUsers := 0
numAdmins := 0
Create the input for and call GetAccountAuthorizationDetails. If there is an error, print an error
message and quit.
user := "User"
input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}}
resp, err := svc.GetAccountAuthorizationDetails(input)
if err != nil {
fmt.Println("Got error getting account details")
fmt.Println(err.Error())
os.Exit(1)
}
Loop through the users. If a user has adminstrator privileges, print their name and increment the number
of users who have adminstrator privileges.
adminName := "AdministratorAccess"
if isAdmin {
fmt.Println(*user.UserName)
numAdmins += 1
}
}
If we did not get all of the users in the first call to GetAccountAuthorizationDetails, loop through
the next set of users and determine which of those have adminstrator privileges.
if isAdmin {
fmt.Println(*user.UserName)
numAdmins += 1
}
}
}
fmt.Println("")
fmt.Println("Found", numAdmins, "admin(s) out of", numUsers, "user(s).")
100
AWS SDK for Go Developer Guide
Managing IAM Access Keys
Scenario
Users need their own access keys to make programmatic calls to the AWS SDK for Go. To fill this need,
you can create, modify, view, or rotate access keys (access key IDs and secret access keys) for IAM users.
By default, when you create an access key its status is Active, which means the user can use the access
key for API calls.
In this example, you use a series of Go routines to manage access keys in IAM. The routines use the AWS
SDK for Go IAM client methods that follow:
• CreateAccessKey
• ListAccessKeys
• GetAccessKeyLastUsed
• UpdateAccessKey
• DeleteAccessKey
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with IAM access keys. To learn more, see Managing Access Keys for IAM Users in the
IAM User Guide.
Create a new Go file named iam_createaccesskey.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
101
AWS SDK for Go Developer Guide
Managing IAM Access Keys
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", *result.AccessKey)
}
Create a new Go file named iam_listaccesskeys.go. You must import the relevant Go and AWS SDK
for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", result)
}
102
AWS SDK for Go Developer Guide
Managing IAM Access Keys
Create a new Go file named iam_accesskeylastused.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call GetAccessKeyLastUsed, passing in the access key ID, and print the results.
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", *result.AccessKeyLastUsed)
}
Create a new Go file with the name iam_updateaccesskey.go. You must import the relevant Go and
AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
103
AWS SDK for Go Developer Guide
Managing IAM Access Keys
Region: aws.String("us-west-2")},
)
Call UpdateAccessKey, passing in the access key ID, status (making it active in this case), and user
name.
_, err = svc.UpdateAccessKey(&iam.UpdateAccessKeyInput{
AccessKeyId: aws.String("ACCESS_KEY_ID"),
Status: aws.String(iam.StatusTypeActive),
UserName: aws.String("USER_NAME"),
})
if err != nil {
fmt.Println("Error", err)
return
}
Create a new Go file named iam_deleteaccesskey.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Error", err)
104
AWS SDK for Go Developer Guide
Managing IAM Account Aliases
return
}
fmt.Println("Success", result)
}
Scenario
You can use a series of Go routines to manage aliases in IAM. The routines use the AWS SDK for Go IAM
client methods that follow:
• CreateAccountAlias
• ListAccountAliases
• DeleteAccountAlias
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with IAM account aliases. To learn more, see Your AWS Account ID and Its Alias in the
IAM User Guide.
Create a new Go file named iam_createaccountalias.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
_, err = svc.CreateAccountAlias(&iam.CreateAccountAliasInput{
AccountAlias: &os.Args[1],
105
AWS SDK for Go Developer Guide
Managing IAM Account Aliases
})
The code takes the new alias as an argument, and then calls CreateAccountAlias with the alias name.
_, err = svc.CreateAccountAlias(&iam.CreateAccountAliasInput{
AccountAlias: &os.Args[1],
})
if err != nil {
fmt.Println("Error", err)
return
}
Create a new Go file named iam_listaccountaliases.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Error", err)
return
}
106
AWS SDK for Go Developer Guide
Working with IAM Policies
Create a new Go file with the name iam_deleteaccountalias.go. You must import the relevant Go
and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
_, err = svc.DeleteAccountAlias(&iam.DeleteAccountAliasInput{
AccountAlias: &os.Args[1],
})
if err != nil {
fmt.Println("Error", err)
return
}
Scenario
You grant permissions to a user by creating a policy, which is a document that lists the actions that a user
can perform and the resources those actions can affect. Any actions or resources that are not explicitly
allowed are denied by default. Policies can be created and attached to users, groups of users, roles
assumed by users, and resources.
In this example, you use a series of Go routines to manage policies in IAM. The routines use the AWS SDK
for Go IAM client methods that follow:
107
AWS SDK for Go Developer Guide
Working with IAM Policies
• CreatePolicy
• GetPolicy
• ListAttachedRolePolicies
• AttachRolePolicy
• DetachRolePolicy
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with IAM policies. To learn more, see Overview of Access Management: Permissions
and Policies in the IAM User Guide.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
Define two structs. The first is the definition of the policies to upload to IAM.
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
108
AWS SDK for Go Developer Guide
Working with IAM Policies
policy := PolicyDocument{
Version: "2012-10-17",
Statement: []StatementEntry{
StatementEntry{
Effect: "Allow",
Action: []string{
"logs:CreateLogGroup", // Allow for creating log groups
},
Resource: "RESOURCE ARN FOR logs:*",
},
StatementEntry{
Effect: "Allow",
// Allows for DeleteItem, GetItem, PutItem, Scan, and UpdateItem
Action: []string{
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Scan",
"dynamodb:UpdateItem",
},
Resource: "RESOURCE ARN FOR dynamodb:*",
},
},
}
b, err := json.Marshal(&policy)
if err != nil {
fmt.Println("Error marshaling policy", err)
return
}
if err != nil {
fmt.Println("Error", err)
return
}
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
109
AWS SDK for Go Developer Guide
Working with IAM Policies
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
// go run iam_getpolicy.go
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call GetPolicy, passing in the ARN for the policy (which is hard coded in this example), and print the
results.
arn := "arn:aws:iam::aws:policy/AWSLambdaExecute"
result, err := svc.GetPolicy(&iam.GetPolicyInput{
PolicyArn: &arn,
})
if err != nil {
fmt.Println("Error", err)
return
}
Then, you'll check the array members to see if the policy you want to attach to the role is already
attached. If the policy isn't attached, you'll call the AttachRolePolicy method to attach it.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
110
AWS SDK for Go Developer Guide
Working with IAM Policies
Paginate through all the role policies. If your role exists on any role policy, you set the pageErr and
return false, stopping the pagination.
// pagination.
err = svc.ListAttachedRolePoliciesPages(
&iam.ListAttachedRolePoliciesInput{
RoleName: &os.Args[1],
},
func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool {
if page != nil && len(page.AttachedPolicies) > 0 {
for _, policy := range page.AttachedPolicies {
if *policy.PolicyName == policyName {
pageErr = fmt.Errorf("%s is already attached to this role",
policyName)
return false
}
}
// We should keep paginating because we did not find our role
return true
}
return false
},
if pageErr != nil {
fmt.Println("Error", pageErr)
return
}
if err != nil {
fmt.Println("Error", err)
return
}
_, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{
PolicyArn: &policyArn,
RoleName: &os.Args[1],
})
if err != nil {
fmt.Println("Unable to attach role policy to role")
return
}
fmt.Println("Role attached successfully")
111
AWS SDK for Go Developer Guide
Working with IAM Policies
Then, check the array members to see if the policy you want to detach from the role is attached. If the
policy is attached, call the DetachRolePolicy method to detach it.
Create a new Go file named iam_detachuserpolicy.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
foundPolicy := false
policyName := "AmazonDynamoDBFullAccess"
Paginate through all the role policies. If the role exists on any role policy, you stop iterating and detach
the role.
if err != nil {
fmt.Println("Error", err)
return
}
if !foundPolicy {
112
AWS SDK for Go Developer Guide
Working with IAM Server Certificates
_, err = svc.DetachRolePolicy(&iam.DetachRolePolicyInput{
PolicyArn: &policyArn,
RoleName: &os.Args[1],
})
if err != nil {
fmt.Println("Unable to detach role policy to role")
return
}
fmt.Println("Role detached successfully")
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
To enable HTTPS connections to your website or application on AWS, you need an SSL/TLS server
certificate. To use a certificate that you obtained from an external provider with your website or
application on AWS, you must upload the certificate to IAM or import it into AWS Certificate Manager.
In this example, you use a series of Go routines to manage policies in IAM. The routines use the AWS SDK
for GoIAM client methods that follow:
• ListServerCertificates
• GetServerCertificate
• UpdateServerCertificate
• DeleteServerCertificate
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with server certificates. To learn more, see Working with Server Certificates in the IAM
User Guide.
Create a new Go file named iam_listservercerts.go. You must import the relevant Go and AWS
SDK for Go packages by adding the following lines.
// go run iam_listservercerts.go
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
113
AWS SDK for Go Developer Guide
Working with IAM Server Certificates
Create a new Go file named iam_getservercert.go. You must import the relevant Go and AWS SDK
for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call GetServerCertificate, passing the name of the certificate, and print the results.
fmt.Println("ServerCertificate:", result)
114
AWS SDK for Go Developer Guide
Working with IAM Server Certificates
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
_, err = svc.UpdateServerCertificate(&iam.UpdateServerCertificateInput{
ServerCertificateName: aws.String("CERTIFICATE_NAME"),
NewServerCertificateName: aws.String("NEW_CERTIFICATE_NAME"),
})
if err != nil {
fmt.Println("Error", err)
return
}
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
115
AWS SDK for Go Developer Guide
AWS KMS Examples
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
)
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call the method to delete the certificate, specifying the name of certificate.
_, err = svc.DeleteServerCertificate(&iam.DeleteServerCertificateInput{
ServerCertificateName: aws.String("CERTIFICATE_NAME"),
})
if err != nil {
fmt.Println("Error", err)
return
}
Examples
Topics
• Creating a CMK in AWS Key Management Service (p. 116)
• Encrypting Data with AWS Key Management Service (p. 117)
• Decrypting a Data Blob in AWS Key Management Service (p. 118)
• Re-encrypting a Data Blob in AWS Key Management Service (p. 119)
import (
116
AWS SDK for Go Developer Guide
Encrypting Data with AWS Key Management Service
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"fmt"
"os"
)
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Got error creating key: ", err)
os.Exit(1)
}
fmt.Println(*result.KeyMetadata.KeyId)
}
Choose Copy to save the code locally. See the complete example on GitHub.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"fmt"
"os"
)
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
117
AWS SDK for Go Developer Guide
Decrypting a Data Blob in AWS Key Management Service
Region: aws.String("us-west-2")},
)
keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
text := "1234567890"
if err != nil {
fmt.Println("Got error encrypting data: ", err)
os.Exit(1)
}
Choose Copy to save the code locally. See the complete example on GitHub.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"fmt"
"os"
)
func main() {
// Initialize a session that the SDK uses to load
// credentials from the shared credentials file ~/.aws/credentials
// and configuration from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
// Encrypted data
blob := []byte("1234567890")
118
AWS SDK for Go Developer Guide
Re-encrypting a Data Blob in
AWS Key Management Service
if err != nil {
fmt.Println("Got error decrypting data: ", err)
os.Exit(1)
}
blob_string := string(result.Plaintext)
fmt.Println(blob_string)
Choose Copy to save the code locally. See the complete example on GitHub.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"fmt"
"os"
)
func main() {
// Initialize a session that the SDK uses to load
// credentials from the shared credentials file ~/.aws/credentials
// and configuration from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
// Encrypted data
blob := []byte("1234567890")
if err != nil {
fmt.Println("Got error re-encrypting data: ", err)
os.Exit(1)
}
Choose Copy to save the code locally. See the complete example on GitHub.
119
AWS SDK for Go Developer Guide
AWS Lambda Examples
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Displaying Information about All Lambda Functions (p. 120)
• Creating a Lambda Function (p. 121)
• Running a Lambda Function (p. 122)
• Configuring a Lambda Function to Receive Notifications (p. 124)
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
"fmt"
"os"
)
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
fmt.Println("Functions:")
120
AWS SDK for Go Developer Guide
Creating a Lambda Function
• Role ARN: resourceArn. In most cases, you need to attach only the AWSLambdaExecute managed
policy to the policy for this role.
• Function entry point: handler
• Runtime: runtime
• Zip file: zipFileName + .zip
• Bucket: bucketName
• Key: zipFileName
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
"flag"
"fmt"
"io/ioutil"
"os"
)
SharedConfigState: session.SharedConfigEnable,
}))
Next, create the structures for the input argument to the CreateFunction function.
S3Bucket: aws.String(bucketName),
S3Key: aws.String(zipFileName),
S3ObjectVersion: aws.String(""),
ZipFile: contents,
}
createArgs := &lambda.CreateFunctionInput{
Code: createCode,
FunctionName: aws.String(functionName),
Handler: aws.String(handler),
Role: aws.String(resourceArn),
Runtime: aws.String(runtime),
}
Finally, call CreateFunction and display a message with the result of the call.
if err != nil {
fmt.Println("Cannot create function: " + err.Error())
121
AWS SDK for Go Developer Guide
Running a Lambda Function
} else {
fmt.Println(result)
}
}
{
"SortBy": "name|time",
"SortOrder": "ascending|descending",
"Number": 50
}
Where:
• SortBy is the criteria for sorting the results. Our example uses time, which means the returned items
are sorted in the order in which they were added to the database.
• SortOrder is the order of sorting. Our example uses descending, which means the most-recent item
is last in the list.
• Number is the maximum number of items to retrieve (the default is 50). Our example uses 10, which
means get the 10 most-recent items.
The output JSON looks like the following when the function succeeds and two items are returned.
{
"statusCode": 200,
"body": {
"result": "success",
"error": ""
"data": [
{
"item": "item1"
},
{
"item": "item2"
}
]
}
}
Where:
• statusCode– An HTTP status code; 200 means the call was successful.
• body– The body of the returned JSON.
• result– The result of the call, either success or failure.
• error– An error message if result is failure; otherwise, an empty string.
• data– The returned results if result is success; otherwise, nil.
• item– An item from the list of results.
122
AWS SDK for Go Developer Guide
Running a Lambda Function
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
"encoding/json"
"fmt"
"os"
"strconv"
)
Next create session and Lambda client we use to invoke the Lambda function.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Next, create the request and payload, and call MyGetItemsFunction. If there is an error, display a
message and quit.
Finally, parse the response, and if successful, print out the items.
123
AWS SDK for Go Developer Guide
Configuring a Lambda Function to Receive Notifications
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Next, we create the structure for the input argument to the AddPermission function.
permArgs := &lambda.AddPermissionInput{
Action: aws.String("lambda:InvokeFunction"),
FunctionName: functionName,
Principal: aws.String("s3.amazonaws.com"),
SourceArn: sourceArn,
StatementId: aws.String("lambda_s3_notification"),
}
Finally, we call AddPermission and display a message with the result of the call.
if err != nil {
fmt.Println("Cannot configure function for notifications")
os.Exit(0)
} else {
fmt.Println(result)
}
124
AWS SDK for Go Developer Guide
Getting a List of Voices
For more information, see Getting Started with the AWS SDK for Go (p. 2) and Configuring the AWS SDK
for Go (p. 4).
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Getting a List of Voices (p. 125)
• Getting a List of Lexicons (p. 125)
• Synthesizing Speech (p. 126)
Create the file pollyDescribeVoices.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/polly"
"fmt"
"os"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create
an Amazon Polly client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := polly.New(sess)
125
AWS SDK for Go Developer Guide
Synthesizing Speech
Create the file pollyListLexicons.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/polly"
"fmt"
"os"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create
an Amazon Polly client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := polly.New(sess)
Call ListLexicons and display the name, alphabet, and language code of each lexicon.
Synthesizing Speech
This example uses the SynthesizeSpeech operation to get the text from a file and produce an MP3 file
containing the synthesized speech.
Create the file pollySynthesizeSpeech.go. Import the packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/polly"
"fmt"
"os"
"strings"
"io"
"io/ioutil"
)
Get the name of the text file from the command line.
if len(os.Args) != 2 {
126
AWS SDK for Go Developer Guide
Amazon S3 Examples
fileName := os.Args[1]
Initialize a session that the SDK will use to load credentials from the shared credentials file ~/.aws/
credentials, load your configuration from the shared configuration file ~/.aws/config, and create
an Amazon Polly client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := polly.New(sess)
Note
The resulting MP3 file is in the MPEG-2 format.
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Performing Basic Amazon S3 Bucket Operations (p. 128)
• Creating Pre-Signed URLs for Amazon S3 Buckets (p. 140)
127
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
In these examples, a series of Go routines are used to perform operations on your Amazon S3 buckets.
The routines use the AWS SDK for Go to perform Amazon S3 bucket operations using the following
methods of the Amazon S3 client class, unless otherwise noted:
• ListBuckets
• CreateBucket
• ListObjects
• Upload (from the s3manager.NewUploader class)
• Download (from the s3manager.NewDownloader class)
• CopyObject
• DeleteObject
• DeleteObjects
• RestoreObject
• DeleteBucket
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with buckets. To learn more, see Working with Amazon S3 Buckets in the Amazon S3
Developer Guide.
128
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
List Buckets
The ListBuckets function lists the buckets in your account.
The following example lists the buckets in your account. There are no command line arguments.
Create the file s3_list_buckets.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
Call ListBuckets. Passing nil means no filters are applied to the returned list. If an error occurs, call
exitErrorf. If no error occurs, loop through the buckets, printing the name and creation date of each
bucket.
fmt.Println("Buckets:")
Create a Bucket
The CreateBucket function creates a bucket in your account.
The following example creates a bucket with the name specified as a command line argument. You must
specify a globally unique name for the bucket.
129
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
Create the file s3_create_bucket.go. Import the following Go and AWS SDK for Go packages.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
The program requires one argument, the name of the bucket to create.
if len(os.Args) != 2 {
exitErrorf("Bucket name missing!\nUsage: %s bucket_name", os.Args[0])
}
bucket := os.Args[1]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new S3 service client.
Call CreateBucket, passing in the bucket name defined previously. If an error occurs, call exitErrorf. If
there are no errors, wait for a notification that the bucket was created.
_, err = svc.CreateBucket(&s3.CreateBucketInput{
Bucket: aws.String(bucket),
})
if err != nil {
exitErrorf("Unable to create bucket %q, %v", bucket, err)
}
err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{
Bucket: aws.String(bucket),
})
If the WaitUntilBucketExists call returns an error, call exitErrorf. If there are no errors, notify the
user of success.
if err != nil {
exitErrorf("Error occurred while waiting for bucket to be created, %v", bucket)
}
130
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
The following example lists the items in the bucket with the name specified as a command line
argument.
Create the file s3_list_objects.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
The program requires one command line argument, the name of the bucket.
if len(os.Args) != 2 {
exitErrorf("Bucket name required\nUsage: %s bucket_name",
os.Args[0])
}
bucket := os.Args[1]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
Call ListObjects, passing in the name of the bucket. If an error occurs, call exitErrorf. If no error
occurs, loop through the items, printing the name, last modified date, size, and storage class of each
item.
131
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
The following example uploads a file to a bucket with the names specified as command line arguments.
Create the file s3_upload_object.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"fmt"
"os"
)
Get the bucket and file name from the command line arguments, open the file, and defer the file closing
until we are done with it. If an error occurs, call exitErrorF.
if len(os.Args) != 3 {
exitErrorf("bucket and file name required\nUsage: %s bucket_name filename",
os.Args[0])
}
bucket := os.Args[1]
filename := os.Args[2]
defer file.Close()
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a NewUploader object.
132
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
// Setup the S3 Upload Manager. Also see the SDK doc for the Upload Manager
// for more information on configuring part size, and concurrency.
//
// http://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#NewUploader
uploader := s3manager.NewUploader(sess)
Upload the file to the bucket. If an error occurs, call exitErrorF. Otherwise, notify the user that the
upload succeeded.
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(filename),
Body: file,
})
if err != nil {
// Print the error and exit.
exitErrorf("Unable to upload %q to %q, %v", filename, bucket, err)
}
The following example downloads an item from a bucket with the names specified as command line
arguments.
Create the file s3_download_object.go. Add the following statements to import the Go and AWS SDK for
Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"fmt"
"os"
)
Get the bucket and file name from the command line arguments. If there aren't two arguments, call
exitErrorf. Otherwise, create the file and defer file closing until we are done downloading. If an error
occurs while creating the file, call exitErrorf.
if len(os.Args) != 3 {
exitErrorf("Bucket and item names required\nUsage: %s bucket_name item_name",
os.Args[0])
133
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
bucket := os.Args[1]
item := os.Args[2]
Initialize the session in us-west-2 that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a NewDownloader object.
sess, _ := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
downloader := s3manager.NewDownloader(sess)
Download the item from the bucket. If an error occurs, call exitErrorf. Otherwise, notify the user that
the download succeeded.
The following example copies an item from one bucket to another with the names specified as command
line arguments.
Create the file s3_copy_object.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
Get the names of the bucket containing the item, the item to copy, and the name of the bucket to which
the item is copied. If there aren't four command line arguments, call exitErrorf.
134
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
if len(os.Args) != 4 {
exitErrorf("Bucket, item, and other bucket names required\nUsage: go run s3_copy_object
bucket item other-bucket")
}
bucket := os.Args[1]
item := os.Args[2]
other := os.Args[3]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
Call CopyObject, with the names of the bucket containing the item, the item to copy, and the name of
the bucket to which the item is copied. If an error occurs, call exitErrorf. If no error occurs, wait for
the item to be copied.
If the WaitUntilObjectExists call returns an error, call exitErrorf. Otherwise, notify the user that
the copy succeeded.
if err != nil {
exitErrorf("Error occurred while waiting for item %q to be copied to bucket %q, %v",
bucket, item, other, err)
}
The following example deletes an item from a bucket with the names specified as command line
arguments.
Create the file s3_delete_object.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
135
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
if len(os.Args) != 3 {
exitErrorf("Bucket and object name required\nUsage: %s bucket_name object_name",
os.Args[0])
}
bucket := os.Args[1]
obj := os.Args[2]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
Call DeleteObject, passing in the names of the bucket and object to delete. If an error occurs, call
exitErrorf. If no error occurs, wait until the object is deleted.
err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(obj),
})
If WaitUntilObjectNotExists returns an error, call exitErrorf. Otherwise, inform the user that the
object was successfully deleted.
136
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
The following example deletes all the items from a bucket with the bucket name specified as a command
line argument.
Create the file s3_delete_objects.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"fmt"
"os"
)
if len(os.Args) != 2 {
exitErrorf("Bucket name required\nUsage: %s BUCKET", os.Args[0])
}
bucket := os.Args[1]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
sess, _ := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
svc := s3.New(sess)
Create a list iterator to iterate through the list of bucket objects, deleting each object. If an error occurs,
call exitErrorf.
Once all of the items in the bucket have been deleted, inform the user that the objects were deleted.
137
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
The following example restores the items in a bucket with the names specified as command line
arguments.
Create the file s3_restore_object.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
The program requires two arguments, the names of the bucket and object to restore.
if len(os.Args) != 3 {
exitErrorf("Bucket name and object name required\nUsage: %s bucket_name object_name",
os.Args[0])
}
bucket := os.Args[1]
obj := os.Args[2]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
Call RestoreObject, passing in the bucket and object names and the number of days to temporarily
restore. If an error occurs, call exitErrorf. Otherwise, inform the user that the bucket should be
restored in the next four hours or so.
138
AWS SDK for Go Developer Guide
Performing Basic Amazon S3 Bucket Operations
Delete a Bucket
The DeleteBucket function deletes a bucket.
The following example deletes the bucket with the name specified as a command line argument.
Create the file s3_delete_bucket.go. Import the following Go and AWS SDK for Go packages.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
The program requires one argument, the name of the bucket to delete. If the argument is not supplied,
call exitErrorf.
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0])
}
bucket := os.Args[1]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new S3 service client.
Call DeleteBucket, passing in the bucket name. If an error occurs, call exitErrorf. If there are no errors,
wait for a notification that the bucket was deleted.
_, err = svc.DeleteBucket(&s3.DeleteBucketInput{
Bucket: aws.String(bucket),
})
if err != nil {
139
AWS SDK for Go Developer Guide
Creating Pre-Signed URLs for Amazon S3 Buckets
err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{
Bucket: aws.String(bucket),
})
If WaitUntilBucketNotExists returns an error, call exitErrorf. Otherwise, inform the user that the
bucket was successfully deleted.
if err != nil {
exitErrorf("Error occurred while waiting for bucket to be deleted, %v", bucket)
}
Scenario
In this example, a series of Go routines are used to obtain a pre-signed URL for an Amazon S3 bucket
using either GetObject or a PUT operation. A pre-signed URL allows you to grant temporary access to
users who don't have permission to directly run AWS operations in your account. A pre-signed URL is
signed with your credentials and can be used by any user.
• Presign
Prerequisites
• You have set up (p. 2) and configured (p. 4) the SDK.
• You are familiar with pre-signed URLs. To learn more, see Uploading Objects Using Pre-Signed URLs in
the Amazon S3 Developer Guide.
The following example generates a pre-signed URL that enables you to temporarily share a file without
making it public. Anyone with access to the URL can view the file.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
140
AWS SDK for Go Developer Guide
Creating Pre-Signed URLs for Amazon S3 Buckets
"log"
"time"
)
req, _ := svc.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String("myBucket"),
Key: aws.String("myKey"),
})
urlStr, err := req.Presign(15 * time.Minute)
if err != nil {
log.Println("Failed to sign request", err)
}
If the SDK has not retrieved your credentials before calling Presign, it will get them to generate the
pre-signed URL.
The following example adds a Body field to generate a pre-signed PUT operation that requires a specific
payload to be uploaded by users.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"log"
"strings"
"time"
)
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
141
AWS SDK for Go Developer Guide
Creating Pre-Signed URLs for Amazon S3 Buckets
req, _ := svc.PutObjectRequest(&s3.PutObjectInput{
Bucket: aws.String("myBucket"),
Key: aws.String("myKey"),
Body: strings.NewReader("EXPECTED CONTENTS"),
})
str, err := req.Presign(15 * time.Minute)
If you omit the Body field, users can write any contents to the given object.
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"encoding/base64"
"fmt"
"crypto/md5"
"strings"
"time"
"net/http"
)
// Downloads an item from an S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run s3_download.go
func main() {
h := md5.New()
content := strings.NewReader("")
content.WriteTo(h)
resp, _ := svc.PutObjectRequest(&s3.PutObjectInput{
Bucket: aws.String("testBucket"),
Key: aws.String("testKey"),
})
md5s := base64.StdEncoding.EncodeToString(h.Sum(nil))
resp.HTTPRequest.Header.Set("Content-MD5", md5s)
142
AWS SDK for Go Developer Guide
Using an Amazon S3 Bucket as a Static Web Host
Scenario
In this example, you use a series of Go routines to configure any of your buckets to act as a static web
host. The routines use the AWS SDK for Go to configure a selected Amazon S3 bucket using these
methods of the Amazon S3 client class:
• GetBucketWebsite
• PutBucketWebsite
• DeleteBucketWebsite
For more information about using an Amazon S3 bucket as a static web host, see Hosting a Static
Website on Amazon S3 in the Amazon S3 Developer Guide.
Prerequisites
• You have set up (p. 2), and configured (p. 4) the AWS SDK for Go.
• You are familiar with hosting static websites on Amazon S3. To learn more, see Hosting a Static
Website on Amazon S3 in the Amazon S3 Developer Guide.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
This routine requires you to pass in an argument containing the name of the bucket for which you want
to get website configuration.
if len(os.Args) != 2 {
143
AWS SDK for Go Developer Guide
Using an Amazon S3 Bucket as a Static Web Host
bucket := os.Args[1]
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials, and create a new S3 service client.
Call GetBucketWebsite to get the bucket configuration. You should check for the
NoSuchWebsiteConfiguration error code, which tells you that the bucket doesn't have a website
configured.
Create a new Go file named s3_create_bucket.go. You must import the relevant Go and AWS SDK for
Go packages by adding the following lines.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
"path/filepath"
)
This routine requires you to pass in an argument containing the name of the bucket and the index suffix
page.
144
AWS SDK for Go Developer Guide
Using an Amazon S3 Bucket as a Static Web Host
if len(os.Args) != 4 {
exitErrorf("bucket name and index suffix page required\nUsage: %s bucket_name
index_page [error_page]",
filepath.Base(os.Args[0]))
}
bucket := fromArgs(os.Args, 1)
indexSuffix := fromArgs(os.Args, 2)
errorPage := fromArgs(os.Args, 3)
Initialize a session that the SDK will use to load configuration, credentials, and region information from
the shared credentials file, ~/.aws/credentials, and create a new S3 service client.
Create the parameters to be passed in to PutBucketWebsite, including the bucket name and index
document details. If the user passed in an error page when calling the routine, also add that to the
parameters.
params := s3.PutBucketWebsiteInput{
Bucket: aws.String(bucket),
WebsiteConfiguration: &s3.WebsiteConfiguration{
IndexDocument: &s3.IndexDocument{
Suffix: aws.String(indexSuffix),
},
},
}
Call PutBucketWebsite, passing in the parameters you just defined. If an error occurs, print the
errordetails and exit the routine.
_, err = svc.PutBucketWebsite(¶ms)
if err != nil {
exitErrorf("Unable to set bucket %q website configuration, %v",
bucket, err)
}
import (
"github.com/aws/aws-sdk-go/aws"
145
AWS SDK for Go Developer Guide
Working with Amazon S3 CORS Permissions
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
"path/filepath"
)
This routine requires you to pass in the name of the bucket for which you want to delete the website
configuration.
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name",
filepath.Base(os.Args[0]))
}
bucket := os.Args[1]
Initialize a session that the SDK will use to load configuration, credentials, and region information from
the shared credentials file, ~/.aws/credentials, and create a new S3 service client.
Call DeleteBucketWebsite and pass in the name of the bucket to complete the action.
_, err = svc.DeleteBucketWebsite(&s3.DeleteBucketWebsiteInput{
Bucket: aws.String(bucket),
})
if err != nil {
exitErrorf("Unable to delete bucket %q website configuration, %v",
bucket, err)
}
Scenario
In this example, a series of Go routines are used to list your Amazon S3 buckets and to configure CORS
and bucket logging. The routines use the AWS SDK for Go to configure a selected Amazon S3 bucket
using these methods of the Amazon S3 client class:
• GetBucketCors
• PutBucketCors
If you are unfamiliar with using CORS configuration with an Amazon S3 bucket, it's worth your time to
read Cross-Origin Resource Sharing (CORS) in the Amazon S3 Developer Guide before proceeding.
146
AWS SDK for Go Developer Guide
Working with Amazon S3 CORS Permissions
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with using CORS configuration with an Amazon S3 bucket. To learn more, see Cross-
Origin Resource Sharing (CORS) in the Amazon S3 Developer Guide.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"flag"
"fmt"
"os"
"strings"
)
This routine configures CORS rules for a bucket by setting the allowed HTTP methods.
It requires the bucket name and can also take a space-separated list of HTTP methods. Using the Go
Language's flag package, it parses the input and validates the bucket name.
if len(bucket) == 0 {
exitErrorf("-b <bucket> Bucket name required")
}
methods := filterMethods(flag.Args())
Notice the helper method, filterMethods, which ensures the methods passed in are uppercase.
return filtered
}
Initialize a session that the SDK will use to load credentials, from the shared credentials file, ~/.aws/
credentials, and create a new S3 service client.
147
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket Policies
rule := s3.CORSRule{
AllowedHeaders: aws.StringSlice([]string{"Authorization"}),
AllowedOrigins: aws.StringSlice([]string{"*"}),
MaxAgeSeconds: aws.Int64(3000),
// Add HTTP methods CORS request that were specified in the CLI.
AllowedMethods: aws.StringSlice(methods),
}
Add the CORSRule to the PutBucketCorsInput structure, call PutBucketCors with that structure,
and print a success or error message.
params := s3.PutBucketCorsInput{
Bucket: aws.String(bucket),
CORSConfiguration: &s3.CORSConfiguration{
CORSRules: []*s3.CORSRule{&rule},
},
}
_, err = svc.PutBucketCors(¶ms)
if err != nil {
// Print the error message
exitErrorf("Unable to set Bucket %q's CORS, %v", bucket, err)
}
Scenario
In this example, you use a series of Go routines to retrieve or set a bucket policy on an Amazon S3
bucket. The routines use the AWS SDK for Go to configure policy for a selected Amazon S3 bucket using
these methods of the Amazon S3 client class:
• GetBucketPolicy
• PutBucketPolicy
• DeleteBucketPolicy
For more information about bucket policies for Amazon S3 buckets, see Using Bucket Policies and User
Policies in the Amazon S3 Developer Guide.
Prerequisites
• You have set up (p. 2), and configured (p. 4) the AWS SDK for Go.
148
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket Policies
• You are familiar with Amazon S3 bucket polices. To learn more, see Using Bucket Policies and User
Policies in the Amazon S3 Developer Guide.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
)
This routine prints the policy for a bucket. If the bucket doesn't exist, or there was an error, an error
message is printed instead. It requires the bucket name as input.
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name",
filepath.Base(os.Args[0]))
}
bucket := os.Args[1]
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials, and create a new S3 service client.
svc := s3.New(sess)
149
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket Policies
case "NoSuchBucketPolicy":
exitErrorf("Bucket %q does not have a policy.", bucket)
}
}
exitErrorf("Unable to get bucket %q policy, %v.", bucket, err)
}
Use Go's JSON package to print the Policy JSON returned by the call.
out := bytes.Buffer{}
policyStr := aws.StringValue(result.Policy)
if err := json.Indent(&out, []byte(policyStr), "", " "); err != nil {
exitErrorf("Failed to pretty print bucket policy, %v.", err)
}
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"encoding/json"
"fmt"
"os"
"path/filepath"
)
Add the main function and parse the arguments to get the bucket name.
func main() {
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name",
filepath.Base(os.Args[0]))
}
bucket := os.Args[1]
Initialize a session that the SDK will use to load configuration, credentials, and region information from
the shared credentials file, ~/.aws/credentials, and create a new S3 service client.
svc := s3.New(sess)
Create a policy using the map interface, filling in the bucket as the resource.
readOnlyAnonUserPolicy := map[string]interface{}{
150
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": []string{
"s3:GetObject",
},
"Resource": []string{
fmt.Sprintf("arn:aws:s3:::%s/*", bucket),
},
},
},
}
Use Go's JSON package to marshal the policy into a JSON value so that it can be sent to S3.
Call the S3 client's PutBucketPolicy to PUT the policy for the bucket and print the results.
_, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: aws.String(bucket),
Policy: aws.String(string(policy)),
})
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
In these examples, a series of Go routines are used to manage ACLs on your Amazon S3 buckets. The
routines use the AWS SDK for Go to perform Amazon S3 bucket operations using the following methods
of the Amazon S3 client class:
151
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
• GetBucketAcl
• GetObjectAcl
• PutBucketAcl
• PutObjectAcl
Prerequisites
• You have set up (p. 2), and configured (p. 4) the AWS SDK for Go.
• You are familiar with Amazon S3 bucket ACLs. To learn more, see Managing Access with ACLs in the
Amazon S3 Developer Guide.
The following example gets the ACLs on a bucket with the name specified as a command line argument.
Create the file s3_get_bucket_acl.go. Add the following statements to import the Go and AWS SDK for Go
packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
This example requires one input parameter, the name of the bucket. If the name is not supplied, call the
error function and exit.
if len(os.Args) != 2 {
exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET")
}
bucket := os.Args[1]
Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/
credentials, the region from the shared configuration file ~/.aws/config, and create a new Amazon S3
service client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
152
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
Call GetBucketAcl, passing in the name of the bucket. If an error occurs, call exitErrorf. If no error
occurs, loop through the results and print out the name, type, and permssion for the grantees.
fmt.Println("Owner:", *result.Owner.DisplayName)
fmt.Println("")
fmt.Println("Grants")
The following example gives a user access by email address to a bucket with the bucket name and email
address specified as command line arguments. The user can also supply a permission argumement.
However, if it isn'o't supplied, the user is given READ access to the bucket.
Create the file s3_put_bucket_acl.go. Add the following statements to import the Go and AWS SDK for
Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
Get the two required input parameters. If the optional permission parameter is supplied, make sure it is
one of the allowed values. If not, print an error message and quit.
if len(os.Args) < 3 {
exitErrorf("Bucket name and email address required; permission optional (READ if
omitted)\nUsage: go run", os.Args[0], "BUCKET EMAIL [PERMISSION]")
153
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
bucket := os.Args[1]
address := os.Args[2]
permission := "READ"
if len(os.Args) == 4 {
permission = os.Args[3]
}
}
Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/
credentials, the region from the shared configuration file ~/.aws/config, and create a new Amazon S3
service client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Get the existing ACLs and append the new user to the list. If there is an error while retrieving the list,
print an error message and quit.
owner := *result.Owner.DisplayName
ownerId := *result.Owner.ID
// Existing grants
grants := result.Grants
Build the parameter list for the call based on the existing ACLs and the new user information.
params := &s3.PutBucketAclInput{
Bucket: &bucket,
AccessControlPolicy: &s3.AccessControlPolicy{
Grants: grants,
Owner: &s3.Owner{
DisplayName: &owner,
ID: &ownerId,
},
},
154
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
Call PutBucketAcl, passing in the parameter list. If an error occurs, display a message and quit.
Otherwise, display a message indicating success.
_, err = svc.PutBucketAcl(params)
if err != nil {
exitErrorf(err.Error())
}
The following example gives everyone read-only access to the items in the bucket with the bucket name
specified as a command line argument.
Create the file s3_make_bucket_public.go. Add the following statements to import the Go and AWS SDK
for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
if len(os.Args) < 2 {
exitErrorf("Bucket name required.\nUsage: go run", os.Args[0], "BUCKET")
}
bucket := os.Args[1]
acl := "public-read"
Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/
credentials the region from the shared configuration file ~/.aws/config, and create a new Amazon S3
service client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := s3.New(sess)
155
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
Create the input for and call PutBucketAcl. If an error occurs, display a message and quit. Otherwise,
display a message indicating success.
params := &s3.PutBucketAclInput{
Bucket: &bucket,
ACL: &acl,
}
The following example gets the ACLs for a bucket item with the bucket and item name specified as
command line arguments.
Create the file s3_get_bucket_object_acl.go. Add the following statements to import the Go and AWS SDK
for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
This example requires two input parameters, the names of the bucket and object. If either name is not
supplied, call the error function and exit.
if len(os.Args) != 3 {
exitErrorf("Bucket and object names required\nUsage: go run", os.Args[0], "BUCKET
OBJECT")
}
bucket := os.Args[1]
key := os.Args[2]
Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/
credentials, the region from the shared configuration file ~/.aws/config, and create a new Amazon S3
service client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
156
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
SharedConfigState: session.SharedConfigEnable,
}))
Call GetObjectAcl, passing in the names of the bucket and object. If an error occurs, call exitErrorf. If
no error occurs, loop through the results and print out the name, type, and permssion for the grantees.
fmt.Println("Owner:", *result.Owner.DisplayName)
fmt.Println("")
fmt.Println("Grants")
The following example gives a user access by email address to a bucket item, with the bucket and item
names and email address specified as command line arguments. The user can also supply a permission
argumement. However, if it isn't supplied, the user is given READ access to the bucket.
Create the file s3_put_bucket_object_acl.go. Add the following statements to import the Go and AWS
SDK for Go packages used in the example.
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
Get the three required input parameters. If the optional permission parameter is supplied, make sure it is
one of the allowed values. If not, print an error message and quit.
if len(os.Args) < 4 {
exitErrorf("Bucket name, object name, and email address required; permission optional
(READ if omitted)\nUsage: go run", os.Args[0], "BUCKET OBJECT EMAIL [PERMISSION]")
157
AWS SDK for Go Developer Guide
Working with Amazon S3 Bucket ACLs
bucket := os.Args[1]
key := os.Args[2]
address := os.Args[3]
permission := "READ"
if len(os.Args) == 5 {
permission = os.Args[4]
Initialize the session that the SDK uses to load credentials from the shared credentials file
<problematic>*</problematic>
~/.aws/credentials, and create a new Amazon S3 service client.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
Build the parameter list for the call based on the existing ACLs and the new user information.
owner := *result.Owner.DisplayName
ownerId := *result.Owner.ID
// Existing grants
grants := result.Grants
params := &s3.PutObjectAclInput{
Bucket: &bucket,
Key: &key,
AccessControlPolicy: &s3.AccessControlPolicy{
Grants: grants,
Owner: &s3.Owner{
DisplayName: &owner,
ID: &ownerId,
},
},
}
158
AWS SDK for Go Developer Guide
Encrypting Amazon S3 Bucket Items
Call PutObjectAcl, passing in the parameter list. If an error occurs, display a message and quit. Otherwise,
display a message indicating success.
_, err = svc.PutObjectAcl(params)
if err != nil {
exitErrorf(err.Error())
}
• You can have Amazon S3 automatically encrypt objects as you upload them to a bucket. Once you
configure a bucket with this option, every object that you upload--from that point on--is encrypted.
• You can encrypt objects yourself before you upload them to a bucket. The disadvantage with this
approach is that you can still upload objects that are not encrypted. We don't show this approach in
the documentation.
• You can have Amazon S3 reject objects that you attempt to upload to a bucket without requesting
Amazon S3 encrypt the items.
Topics
• Setting Default Server-Side Encryption for an Amazon S3 Bucket (p. 159)
• Requiring Encryption on the Server to Upload Amazon S3 Bucket Objects (p. 160)
• Encrypting an Amazon S3 Bucket Object on the Server Using AWS KMS (p. 162)
The only exception is if the user configures their request to explicitly use server-side encryption. In that
case, the specified encryption takes precedence.
import (
"github.com/aws/aws-sdk-go/aws"
159
AWS SDK for Go Developer Guide
Encrypting Amazon S3 Bucket Items
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
)
Get the KMS key from the command line, where key is a KMS key ID as created in the Creating a CMK in
AWS Key Management Service (p. 116) example, and set the bucket name.
if len(os.Args) != 2 {
fmt.Println("You must supply a key")
os.Exit(1)
}
key := os.Args[1]
bucket := "myBucket"
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := s3.New(sess)
Create the input for and call PutBucketEncryption, and display a success message.
Avoid using this configuration option if you use default server-side encryption as described in Setting
Default Server-Side Encryption for an Amazon S3 Bucket (p. 159) as they could conflict and result in
unexpected results.
import (
160
AWS SDK for Go Developer Guide
Encrypting Amazon S3 Bucket Items
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
"encoding/json"
)
Set the name of the bucket, create a session, and create an Amazon S3 client.
SharedConfigState: session.SharedConfigEnable,
}))
svc := s3.New(sess)
Create an Amazon S3 policy that requires server-side KMS encryption on objects uploaded to the bucket.
"Version": "2012-10-17",
"Statement": []map[string]interface{}{
{
"Sid": "DenyIncorrectEncryptionHeader",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::" + bucket + "/*",
"Condition": map[string]interface{}{
"StringNotEquals": map[string]interface{}{
"s3:x-amz-server-side-encryption": "aws:kms",
},
},
},
{
"Sid": "DenyUnEncryptedObjectUploads",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::" + bucket + "/*",
"Condition": map[string]interface{}{
"Null": map[string]interface{}{
"s3:x-amz-server-side-encryption": "true",
},
},
},
},
}
Convert the policy into JSON, create the input for and call PutBucketPolicy, apply the policy to the
bucket, and print a success message.
if err != nil {
Bucket: aws.String(bucket),
Policy: aws.String(string(policy)),
}
if err != nil {
161
AWS SDK for Go Developer Guide
Encrypting Amazon S3 Bucket Items
Note that this differs from Setting Default Server-Side Encryption for an Amazon S3 Bucket (p. 159), is
in that case, the objects are encrypted without you having to explicitly perform the operation.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"fmt"
"os"
"strings"
)
Get the KMS key from the command line, where key is a KMS key ID as created in the Creating a CMK in
AWS Key Management Service (p. 116) example, and set the bucket and object names.
if len(os.Args) != 2 {
fmt.Println("You must supply a key")
os.Exit(1)
}
key := os.Args[1]
bucket := "myBucket"
object := "myItem"
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := s3.New(sess)
Create input for and call put_object. Notice that the server_side_encryption property is set to
aws:kms, indicating that Amazon S3 encrypts the object using AWS KMS, and display a success message
to the user.
input := &s3.PutObjectInput{
Body: strings.NewReader(object),
Bucket: aws.String(bucket),
Key: aws.String(object),
ServerSideEncryption: aws.String("aws:kms"),
SSEKMSKeyId: aws.String(key),
}
162
AWS SDK for Go Developer Guide
Amazon SES Examples
_, err := svc.PutObject(input)
fmt.Println("Added object " + object + " to bucket " + bucket + " with AWS KMS encryption")
Topics
• Listing Valid Amazon SES Email Addresses (p. 163)
• Verifying an Email Address in Amazon SES (p. 164)
• Sending a Message to an Email Address in Amazon SES (p. 165)
• Deleting an Email Address in Amazon SES (p. 167)
• Getting Amazon SES Statistics (p. 168)
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ses"
)
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
163
AWS SDK for Go Developer Guide
Verifying an Email Address in Amazon SES
verified, err :=
svc.GetIdentityVerificationAttributes(&ses.GetIdentityVerificationAttributesInput{Identities:
e})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
package main
import (
"fmt"
const (
// Replace [email protected] with your "From" address.
// This address must be verified with Amazon SES.
Sender = "[email protected]"
func main() {
// Create a new session in the us-west-2 region.
// Replace us-west-2 with the AWS Region you're using for Amazon SES.
sess, err := session.NewSession(&aws.Config{
Region:aws.String("us-west-2")},
)
164
AWS SDK for Go Developer Guide
Sending a Message to an Email Address in Amazon SES
switch aerr.Code() {
case ses.ErrCodeMessageRejected:
fmt.Println(ses.ErrCodeMessageRejected, aerr.Error())
case ses.ErrCodeMailFromDomainNotVerifiedException:
fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error())
case ses.ErrCodeConfigurationSetDoesNotExistException:
fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
package main
import (
"fmt"
const (
// Replace [email protected] with your "From" address.
// This address must be verified with Amazon SES.
Sender = "[email protected]"
165
AWS SDK for Go Developer Guide
Sending a Message to an Email Address in Amazon SES
func main() {
// Create a new session in the us-west-2 region.
// Replace us-west-2 with the AWS Region you're using for Amazon SES.
sess, err := session.NewSession(&aws.Config{
Region:aws.String("us-west-2")},
)
166
AWS SDK for Go Developer Guide
Deleting an Email Address in Amazon SES
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
package main
import (
"fmt"
"os"
const (
// Replace [email protected] with your "From" address
Sender = "[email protected]"
func main() {
// Create a new session in the us-west-2 region
// Replace us-west-2 with the AWS Region you're using for Amazon SES
sess, err := session.NewSession(&aws.Config{
Region:aws.String("us-west-2")},
)
if err != nil {
fmt.Println("Got error creating SES session:")
fmt.Println(err.Error())
os.Exit(1)
}
167
AWS SDK for Go Developer Guide
Getting Amazon SES Statistics
fmt.Println(delErr.Error())
os.Exit(1)
}
package main
import (
//go get -u github.com/aws/aws-sdk-go
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ses"
"fmt"
)
func main() {
// Initialize a session that the SDK uses to load
// credentials from the shared credentials file ~/.aws/credentials
// and configuration from the shared configuration file ~/.aws/config.
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
dps := result.SendDataPoints
168
AWS SDK for Go Developer Guide
Amazon SNS Examples
Topics
• Listing Your Amazon SNS Topics (p. 169)
• Creating an Amazon SNS Topic (p. 169)
• List Your Amazon SNS Subscriptions (p. 170)
• Subscribe to an Amazon SNS Topic (p. 171)
• Sending a Message to All Amazon SNS Topic Subscribers (p. 172)
package main
import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
"fmt"
"os"
)
func main() {
// Initialize a session that the SDK will use to load
// credentials from the shared credentials file. (~/.aws/credentials).
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := sns.New(sess)
package main
169
AWS SDK for Go Developer Guide
List Your Amazon SNS Subscriptions
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("You must supply a topic name")
fmt.Println("Usage: go run SnsCreateTopic.go TOPIC")
os.Exit(1)
}
svc := sns.New(sess)
fmt.Println(*result.TopicArn)
}
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
"flag"
"fmt"
"os"
)
func main() {
emailPtr := flag.String("e", "", "The email address of the user subscribing to the
topic")
topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes")
flag.Parse()
email := *emailPtr
topicArn := *topicPtr
170
AWS SDK for Go Developer Guide
Subscribe to an Amazon SNS Topic
svc := sns.New(sess)
fmt.Println(*result.SubscriptionArn)
}
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
"flag"
"fmt"
"os"
)
func main() {
emailPtr := flag.String("e", "", "The email address of the user subscribing to the
topic")
topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes")
flag.Parse()
email := *emailPtr
topicArn := *topicPtr
171
AWS SDK for Go Developer Guide
Sending a Message to All Amazon SNS Topic Subscribers
svc := sns.New(sess)
fmt.Println(*result.SubscriptionArn)
}
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
)
// usage:
// go run sns_publish_to_topic.go
func main() {
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
})
if err != nil {
fmt.Println("NewSession error:", err)
return
}
client := sns.New(sess)
input := &sns.PublishInput{
Message: aws.String("Hello world!"),
TopicArn: aws.String("arn:aws:sns:us-west-2:123456789012:YourTopic"),
}
172
AWS SDK for Go Developer Guide
Amazon SQS Examples
fmt.Println(result)
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Topics
• Using Amazon SQS Queues (p. 173)
• Sending and Receiving Messages in Amazon SQS (p. 177)
• Managing Visibility Timeout in Amazon SQS Queues (p. 181)
• Enabling Long Polling in Amazon SQS Queues (p. 182)
• Using Dead Letter Queues in Amazon SQS (p. 187)
• Setting Attributes on an Amazon SQS Queue (p. 188)
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
These examples demonstrate how to work with Amazon SQS queues.
The code uses these methods of the Amazon SQS client class:
• CreateQueue
• ListQueues
• GetQueueUrl
173
AWS SDK for Go Developer Guide
Using Amazon SQS Queues
• DeleteQueue
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with using Amazon SQS. To learn more, see How Queues Work in the Amazon SQS
Developer Guide.
List Queues
Create a new Go file named sqs_listqueues.go. You must import the relevant Go and AWS SDK for
Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
// go run sqs_listqueues.go
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call ListQueues passing in nil to return all queues. Print any errors or a success message and loop
through the queue URLs to print them.
fmt.Println("Success")
// As these are pointers, printing them out directly would not be useful.
for i, urls := range result.QueueUrls {
// Avoid dereferencing a nil pointer.
if urls == nil {
continue
}
fmt.Printf("%d: %s\n", i, *urls)
}
Create Queues
Create a new Go file named sqs_createqueues.go. You must import the relevant Go and AWS SDK for
Go packages by adding the following lines.
174
AWS SDK for Go Developer Guide
Using Amazon SQS Queues
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call CreateQueue passing in the new queue name and queue attributes. Print any errors or a success
message.
fmt.Println("Success", *result.QueueUrl)
}
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess, err := session.NewSession(&aws.Config{
175
AWS SDK for Go Developer Guide
Using Amazon SQS Queues
Region: aws.String("us-west-2")},
)
Call GetQueueUrl passing in the queue name. Print any errors or a success message.
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", *result.QueueUrl)
}
Delete a Queue
Create a new Go file named sqs_deletequeue.go. You must import the relevant Go and AWS SDK for
Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Call DeleteQueue passing in the queue name. Print any errors or a success message.
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", result)
}
176
AWS SDK for Go Developer Guide
Sending and Receiving Messages in Amazon SQS
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
The Scenario
These examples demonstrate sending, receiving, and deleting messages from an Amazon SQS queue.
The code uses these methods of the Amazon SQS client class:
• SendMessage
• ReceiveMessage
• DeleteMessage
• GetQueueUrl
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with the details of Amazon SQS messages. To learn more, see Sending a Message to
an Amazon SQS Queue and Receiving and Deleting a Message from an Amazon SQS Queue in the
Amazon SQS Developer Guide.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
177
AWS SDK for Go Developer Guide
Sending and Receiving Messages in Amazon SQS
svc := sqs.New(sess)
Now you're ready to send your message. In the example, the message input passed to SendMessage
represents information about a fiction best seller for a particular week and defines title, author, and
weeks on the list values.
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", *result.MessageId)
}
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
178
AWS SDK for Go Developer Guide
Sending and Receiving Messages in Amazon SQS
svc := sqs.New(sess)
Now you're ready to receive a message from a queue specified by a queue URL. In the example, the qURL
variable would hold the URL for the queue containing the message.
qURL := "QueueURL"
if err != nil {
fmt.Println("Error", err)
return
}
if len(result.Messages) == 0 {
fmt.Println("Received no messages")
return
}
After retrieving the message, delete it from the queue with DeleteMessage, passing the
ReceiptHandle returned from the previous call.
if err != nil {
fmt.Println("Delete Error", err)
return
}
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"flag"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
179
AWS SDK for Go Developer Guide
Sending and Receiving Messages in Amazon SQS
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Get the queue name and timeout passed from the command.
func main() {
var name string
var timeout int64
flag.StringVar(&name, "n", "", "Queue name")
flag.Int64Var(&timeout, "t", 20, "(Optional) Timeout in seconds for long polling")
flag.Parse()
if len(name) == 0 {
flag.PrintDefaults()
exitErrorf("Queue name required")
}
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
Get the Queue. You need to convert the queue name into a URL. You can use the GetQueueUrl API call
to retrieve the URL. This is needed for receiving messages from the queue. Print any errors.
180
AWS SDK for Go Developer Guide
Managing Visibility Timeout in Amazon SQS Queues
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
This example manages visibility timeout with Amazon SQS queues. It uses these methods of the Amazon
SQS client class:
• CreateQueue
• ListQueues
• GetQueueUrl
• DeleteQueue
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with using Amazon SQS visibility timeout. To learn more, see Visibility Timeout in the
Amazon SQS Developer Guide.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
181
AWS SDK for Go Developer Guide
Enabling Long Polling in Amazon SQS Queues
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Get a message from the queue. Call ReceiveMessage. Pass in the URL of the queue to return details of
the next message in the queue. Print any errors, or a message if no message was received.
qURL := "QueueURL"
if err != nil {
fmt.Println("Error", err)
return
}
If a message was returned, use its receipt handle to set the timeout to 30 seconds.
duration := int64(30)
resultVisibility, err := svc.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{
ReceiptHandle: result.Messages[0].ReceiptHandle,
QueueUrl: &qURL,
VisibilityTimeout: &duration,
})
if err != nil {
fmt.Println("Visibility Error", err)
return
}
182
AWS SDK for Go Developer Guide
Enabling Long Polling in Amazon SQS Queues
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
Long polling reduces the number of empty responses by allowing Amazon SQS to wait a specified time
for a message to become available in the queue before sending a response. Also, long polling eliminates
false empty responses by querying all of the servers instead of a sampling of servers. To enable long
polling, you must specify a non-zero wait time for received messages. You can do this by setting the
ReceiveMessageWaitTimeSeconds parameter of a queue or by setting the WaitTimeSeconds
parameter on a message when it is received.
The code uses these methods of the Amazon SQS client class:
• SetQueueAttributes
• ReceiveMessage
• CreateQueue
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with Amazon SQS polling. To learn more, see Long Polling in the Amazon SQS
Developer Guide.
Create a new Go file named sqs_longpolling_create_queue.go. You must import the relevant Go
and AWS SDK for Go packages by adding the following lines.
package main
import (
"flag"
"fmt"
"os"
"strconv"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
func main() {
var name string
var timeout int
flag.StringVar(&name, "n", "", "Queue name")
flag.IntVar(&timeout, "t", 20, "(Optional) Timeout in seconds for long polling")
flag.Parse()
183
AWS SDK for Go Developer Guide
Enabling Long Polling in Amazon SQS Queues
if len(name) == 0 {
flag.PrintDefaults()
exitErrorf("Queue name required")
}
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
Create the queue with long polling enabled. Print any errors or a success message.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"flag"
"fmt"
"os"
"strconv"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
This example takes two flags, the -n flag is the queue name, and the -t flag contains the timeout value.
184
AWS SDK for Go Developer Guide
Enabling Long Polling in Amazon SQS Queues
func main() {
var name string
var timeout int
flag.StringVar(&name, "n", "", "Queue name")
flag.IntVar(&timeout, "t", 20, "(Optional) Timeout in seconds for long polling")
flag.Parse()
if len(name) == 0 {
flag.PrintDefaults()
exitErrorf("Queue name required")
}
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
You need to convert the queue name into a URL. Make the GetQueueUrl API call to retrieve the URL.
This is needed for setting attributes on the queue.
Update the queue to enable long polling with a call to SetQueueAttributes, passing in the queue
URL. Print any errors or a success message.
_, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{
QueueUrl: resultURL.QueueUrl,
Attributes: aws.StringMap(map[string]string{
"ReceiveMessageWaitTimeSeconds": strconv.Itoa(timeout),
}),
})
if err != nil {
exitErrorf("Unable to update queue %q, %v.", name, err)
}
185
AWS SDK for Go Developer Guide
Enabling Long Polling in Amazon SQS Queues
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"flag"
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
This example takes two flags, the -n flag is the queue name, and the -t flag contains the timeout value.
func main() {
var name string
var timeout int64
flag.StringVar(&name, "n", "", "Queue name")
flag.Int64Var(&timeout, "t", 20, "(Optional) Timeout in seconds for long polling")
flag.Parse()
if len(name) == 0 {
flag.PrintDefaults()
exitErrorf("Queue name required")
}
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
You need to convert the queue name into a URL. Make the GetQueueUrl API call to retrieve the URL.
This is needed for setting attributes on the queue.
Receive a message from the queue with long polling enabled with a call to ReceiveMessage, passing in
the queue URL. Print any errors or a success message.
186
AWS SDK for Go Developer Guide
Using Dead Letter Queues in Amazon SQS
}),
MaxNumberOfMessages: aws.Int64(1),
MessageAttributeNames: aws.StringSlice([]string{
"All",
}),
WaitTimeSeconds: aws.Int64(timeout),
})
if err != nil {
exitErrorf("Unable to receive message from queue %q, %v.", name, err)
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
Scenario
A dead letter queue is one that other (source) queues can target for messages that can't be processed
successfully. You can set aside and isolate these messages in the dead letter queue to determine why
their processing didn't succeed. You must individually configure each source queue that sends messages
to a dead letter queue. Multiple queues can target a single dead letter queue.
The code uses this method of the Amazon SQS client class:
• SetQueueAttributes
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with Amazon SQS dead letter queues. To learn more, see Using Amazon SQS Dead
Letter Queues in the Amazon SQS Developer Guide.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
187
AWS SDK for Go Developer Guide
Setting Attributes on an Amazon SQS Queue
package main
import (
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
func main() {
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
Define the redrive policy for the queue, then marshal the policy to use as input for the
SetQueueAttributes call.
policy := map[string]string{
"deadLetterTargetArn": "SQS_QUEUE_ARN",
"maxReceiveCount": "10",
}
b, err := json.Marshal(policy)
if err != nil {
fmt.Println("Failed to marshal policy:", err)
return
}
if err != nil {
fmt.Println("Error", err)
return
}
fmt.Println("Success", result)
}
You can download complete versions of these example files from the aws-doc-sdk-examples repository
on GitHub.
188
AWS SDK for Go Developer Guide
Setting Attributes on an Amazon SQS Queue
Scenario
This example updates an existing Amazon SQS queue to use long polling.
Long polling reduces the number of empty responses by allowing Amazon SQS to wait a specified time
for a message to become available in the queue before sending a response. Also, long polling eliminates
false empty responses by querying all of the servers instead of a sampling of servers. To enable long
polling, you must specify a non-zero wait time for received messages. You can do this by setting the
ReceiveMessageWaitTimeSeconds parameter of a queue or by setting the WaitTimeSeconds parameter on
a message when it is received.
The code uses these methods of the Amazon SQS client class:
• GetQueueUrl
• SetQueueAttributes
If you are unfamiliar with using Amazon SQS long polling, you should read Long Polling in the Amazon
SQS Developer Guide before proceeding.
Prerequisites
• You have set up (p. 2) and configured (p. 4) the AWS SDK for Go.
• You are familiar with using Amazon SQS long polling. To learn more, see Long Polling in the Amazon
SQS Developer Guide.
You must import the relevant Go and AWS SDK for Go packages by adding the following lines.
package main
import (
"flag"
"fmt"
"os"
"strconv"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
func main() {
var name string
var timeout int
flag.StringVar(&name, "n", "", "Queue name")
flag.IntVar(&timeout, "t", 20, "(Optional) Timeout in seconds for long polling")
flag.Parse()
if len(name) == 0 {
flag.PrintDefaults()
189
AWS SDK for Go Developer Guide
Amazon WorkDocs Examples
Initialize a session that the SDK will use to load credentials from the shared credentials file, ~/.aws/
credentials.
Get the queue. You need to convert the queue name into a URL. You can use the GetQueueUrl API call
to retrieve the URL. This is needed for setting attributes on the queue. Print any errors.
_, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{
QueueUrl: resultURL.QueueUrl,
Attributes: aws.StringMap(map[string]string{
"ReceiveMessageWaitTimeSeconds": strconv.Itoa(timeout),
}),
})
if err != nil {
exitErrorf("Unable to update queue %q, %v.", name, err)
}
You need your organization ID to use these examples. Get you organization ID from the AWS console
using the following steps:
190
AWS SDK for Go Developer Guide
Listing Users
Examples
Topics
• Listing Users (p. 191)
• Listing User Docs (p. 192)
Listing Users
The following example lists the names of all users, or lists additional details about a user if a user name
is specified on the command line. Choose Copy to save the code locally, or see the link to the complete
example at the end of this topic.
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/workdocs"
"flag"
"fmt"
• flag is for getting user input, in this case the name of the user
• fmt is for formatting output
• session is for creating a session
• workdocs is for using the WorkDocs APIs
Create the input arguments for the DescribeUsers method and add your organization ID.
input := new(workdocs.DescribeUsersInput)
If we have a user name, add that to the input arguments so we only get information about that user.
191
AWS SDK for Go Developer Guide
Listing User Docs
flag.Parse()
Run the DescribeUsers method and display the information for the user or all users.
if err != nil {
fmt.Println("Error getting user info", err)
return
}
if *user_ptr == "" {
fmt.Println("Found", *result.TotalNumberOfUsers, "users")
fmt.Println("")
}
if *user_ptr != "" {
fmt.Println("Firstname: " + *user.GivenName)
fmt.Println("Lastname: " + *user.Surname)
fmt.Println("Email: " + *user.EmailAddress)
fmt.Println("Root folder " + *user.RootFolderId)
}
fmt.Println("")
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/workdocs"
"flag"
"fmt"
• flag is for getting user input, in this case the name of the user
• fmt is for formatting output
• session is for creating a session
• workdocs is for using the WorkDocs APIs
192
AWS SDK for Go Developer Guide
Listing User Docs
Check that we have a user name, and get the root folder for that user.
input := new(workdocs.DescribeUsersInput)
input.OrganizationId = &org_id
input.Query = user_ptr
if err != nil {
fmt.Println("Error getting user info", err)
return
}
if *result.TotalNumberOfUsers == 1 {
for _, user := range result.Users {
folder_id = *user.RootFolderId
Run the DescribeFolderContents method and display the name, size, and last modified information
for each document.
if err != nil {
fmt.Println("Error getting docs for user", err)
return
}
193
AWS SDK for Go Developer Guide
Amazon CloudFront URL Signer
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 in the
Amazon CloudFront Developer Guide.
The following example creates a signed URL that's valid for one hour after it is created.
For more information about the signing utility, see the sign package in the AWS SDK for Go API Reference.
The following example converts a structure to an Amazon DynamoDBAttributeValues map and then
puts the data to the exampleTable.
194
AWS SDK for Go Developer Guide
Amazon Elastic Compute Cloud Metadata
//...
For more information about the converter utility, see the dynamodbattribute package in the AWS SDK for
Go API Reference.
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).
For a list of all metadata categories, see Instance Metadata Categories in the Amazon EC2 User Guide for
Linux Instances.
For more information about the EC2 metadata utility, see the ec2metadata package in the AWS SDK for
Go API Reference.
195
AWS SDK for Go Developer Guide
Amazon S3 Transfer Managers
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.
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 package in the AWS
SDK for Go API Reference.
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.
196
AWS SDK for Go Developer Guide
Upload Manager
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.
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())
}
}
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], "<local path> <bucket> <prefix>")
}
localPath = os.Args[1]
bucket = os.Args[2]
prefix = os.Args[3]
}
197
AWS SDK for Go Developer Guide
Upload Manager
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)
}()
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"
198
AWS SDK for Go Developer Guide
Download Manager
// 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)
}
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.
downloader := s3manager.NewDownloader(session.New())
numBytes, err := downloader.Download(downloadFile,
&s3.GetObjectInput{
Bucket: &downloadBucket,
Key: &downloadFileKey,
})
199
AWS SDK for Go Developer Guide
Download Manager
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 package in the AWS
SDK for Go API Reference.
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 = "MyBucket" // 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)
}
200
AWS SDK for Go Developer Guide
Download Manager
return true
}
201
AWS SDK for Go Developer Guide
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 file in
the aws/aws-sdk-go repository in GitHub.
Added a new topic for handling service errors from GitHub repository.
September 28, 2016
202