• 沒有找到結果。

Run Example Code

在文檔中 AWS SDK for Go (version 1) (頁 21-200)

Step 1: Set up Your AWS Account to Use AWS Cloud9

Start to use AWS Cloud9 by signing in to the AWS Cloud9 console as an AWS Identity and Access

Management (IAM) entity (for example, an IAM user) in your AWS account who has access permissions for AWS Cloud9.

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.

Step 2: Set up Your AWS Cloud9 Development Environment

After you sign in to the AWS Cloud9 console, use the console to create an AWS Cloud9 development environment. After you create the environment, AWS Cloud9 opens the IDE for that environment.

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.

Step 3: Set up the AWS SDK for Go

After AWS Cloud9 opens the IDE for your development environment, use the IDE to set up the AWS SDK for Go in your environment, as follows.

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

wget https://storage.googleapis.com/golang/go1.9.3.linux-amd64.tar.gz # Download the Go installer.

sudo tar -C /usr/local -xzf ./go1.9.3.linux-amd64.tar.gz # Install Go.

rm ./go1.9.3.linux-amd64.tar.gz # Delete the Go installer, as you no longer need it.

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

Step 4: Download Example Code

Use the terminal you opened in the previous step to download example code for the AWS SDK for Go into the AWS Cloud9 development environment.

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.

Step 5: Run Example Code

git clone https://github.com/awsdocs/aws-doc-sdk-examples.git

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

Step 5: Run Example Code

To run code in your AWS Cloud9 development environment, see Run Your Code in the AWS Cloud9 User Guide.

Concurrency

Using Sessions to Configure Service Clients in the AWS SDK for Go

In the AWS SDK for Go, a session is an object that contains configuration information for service clients (p. 21). which you use to interact with AWS services. For example, sessions can include

information about the region where requests will be sent, which credentials to use, or additional request handlers. Whenever you create a service client, you must specify a session. For more information about sessions, see the session package in the AWS SDK for Go API Reference.

Sessions can be shared across all service clients that share the same base configuration. The session is built from the SDK’s default configuration and request handlers.

You should cache sessions when possible. This is because creating a new session loads all configuration values from the environment and configuration files each time the session is created. Sharing the session value across all of your service clients ensures the configuration is loaded the fewest number of times.

Concurrency

Sessions are safe to use concurrently as long as the session isn’t being modified. The SDK doesn’t modify the session once the session is created. Creating service clients concurrently from a shared session is safe.

Sessions with a Shared Configuration File

Using the previous method, you can create sessions that load the additional configuration file only if the AWS_SDK_LOAD_CONFIG environment variable is set. Alternatively you can explicitly create a session with a shared configuration enabled. To do this, you can use NewSessionWithOptions to configure how the session is created. Using the NewSessionWithOptions with SharedConfigState set to SharedConfigEnable will create the session as if the AWS_SDK_LOAD_CONFIG environment variable was set.

Creating Sessions

When you create a session, you can pass in optional aws.Config values that override the default or that override the current configuration values. This allows you to provide additional or case-based configuration as needed.

By default NewSession only loads credentials from the shared credentials file (~/.aws/credentials).

If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value, the session is created from the configuration values from the shared configuration (~/.aws/config) and shared credentials (~/.aws/credentials) files. See Sessions with a Shared Configuration File (p. 18) 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.

Create Sessions with Option Overrides

sess, err := session.NewSession()

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.

sess, err := session.NewSession(&aws.Config{

Region: aws.String("us-east-2")}, )

Create an Amazon S3 client instance from a session:

sess, err := session.NewSession() if err != nil {

// Handle Session creation error }svc := s3.New(sess)

Create Sessions with Option Overrides

In addition to NewSession, you can create sessions using NewSessionWithOptions. This function allows you to control and override how the session will be created through code, instead of being driven by environment variables only.

Use NewSessionWithOptions when you want to provide the config profile, or override the shared credentials state (AWS_SDK_LOAD_CONFIG).

// Equivalent to session.New

sess, err := session.NewSessionWithOptions(session.Options{}) // Specify profile to load for the session's config

sess, err := session.NewSessionWithOptions(session.Options{

Profile: "profile_name", })

// Specify profile for config and region for requests sess, err := session.NewSessionWithOptions(session.Options{

Config: aws.Config{Region: aws.String("us-east-2")}, Profile: "profile_name",

})

// Force enable Shared Config support

sess, err := session.NewSessionWithOptions(session.Options{

SharedConfigState: SharedConfigEnable, })

// Assume an IAM role with MFA prompting for token code on stdin sess := session.Must(session.NewSessionWithOptions(session.Options{

AssumeRoleTokenProvider: stscreds.StdinTokenProvider, SharedConfigState: SharedConfigEnable,

}))

Deprecated New

The New function has been deprecated because it doesn’t provide a good way to return errors that occur when loading the configuration files and values. Because of this, NewSession was created so errors can be retrieved when creating a session fails.

Shared Configuration Fields

Shared Configuration Fields

By default, the SDK loads credentials from the shared credentials file ~/.aws/credentials. Any other configuration values are provided by the environment variables, SDK defaults, and user-provided aws.config values.

If the AWS_SDK_LOAD_CONFIG environment variable is set, or the SharedConfigEnable option is used to create the session (as shown in the following example), additional configuration information is also loaded from the shared configuration file (~/.aws/config), if it exists. If any configuration setting value differs between the two files, the value from the shared credentials file (~/.aws/credentials) takes precedence.

sess := session.Must(session.NewSessionWithOptions(session.Options{

SharedConfigState: session.SharedConfigEnable, }))

See the session package’s documentation 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.

Adding Request Handlers

You can add handlers to a session for processing HTTP requests. All service clients that use the session inherit the handlers. For example, the following handler logs every request and its payload made by a service client.

// Create a session, and add additional handlers for all service // clients created with the Session to inherit. Adds logging handler.

sess, err := session.NewSession()

sess.Handlers.Send.PushFront(func(r *request.Request) { // Log every request made and its payload

logger.Println("Request: %s/%s, Payload: %s",

r.ClientInfo.ServiceName, r.Operation, r.Params) })

Copying a Session

You can use the Copy method to create copies of sessions. Copying sessions is useful when you want to create multiple sessions that have similar settings. Each time you copy a session, you can specify different values for any field. For example, the following snippet copies the sess session while overriding the Region field to us-east-2:

usEast2Sess := sess.Copy(&aws.Config{Region: aws.String("us-east-2")})

Constructing a Service

Using the AWS SDK for Go with AWS Services

To make calls to an AWS service, you must first construct a service client instance with a session. A service client provides low-level access to every API action for that service. For example, you create an Amazon S3 service client to make calls to Amazon S3.

When you call service operations, you pass in input parameters as a struct. A successful call usually results in an output struct that you can use. For example, after you successfully call an Amazon S3 create bucket action, the action returns an output struct with the bucket’s location.

For the list of service clients, including their methods and parameters, see the AWS SDK for Go API Reference.

Constructing a Service

To construct a service client instance, use the NewSession() function. The following example creates an Amazon S3 service client.

sess, err := session.NewSession() if err != nil {

fmt.Println("Error creating session ", err) return

}svc := s3.New(sess)

After you have a service client instance, you can use it to call service operations. For more information about configurations, see Configuring the AWS SDK for Go (p. 5).

When you create a service client, you can pass in custom configurations so that you don’t need to create a session for each configuration. The SDK merges the two configurations, overriding session values with your custom configuration. For example, in the following snippet, the Amazon S3 client uses the mySession session but overrides the Region field with a custom value (us-west-2):

svc := s3.New(mySession, aws.NewConfig().WithRegion("us-west-2"))

Tagging Service Resources

You can tag service resources, such as Amazon S3 buckets, so that you can determine the costs of your service resources at whatever level of granularity you require.

The following example shows how to tag the Amazon S3 bucket MyBucket with Cost Center tag with the value 123456 and Stack tag with the value MyTestStack.

package main import (

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() {

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")}, putInput := &s3.PutBucketTaggingInput{

Bucket: aws.String(bucket),

_, err = svc.PutBucketTagging(putInput) if err != nil { getInput := &s3.GetBucketTaggingInput{

Bucket: aws.String(bucket), }

result, err := svc.GetBucketTagging(getInput) if err != nil {

fmt.Println(err.Error()) return

}

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("")

for _, t := range result.TagSet { fmt.Println(" Key: ", *t.Key) fmt.Println(" Value:", *t.Value) fmt.Println("")

} } else {

fmt.Println("Did not find any tags") }

}

Note that if a tag of the same name already exists, its value is overwritten by the new value.

Getting the HTTP Request and Response with Each Service Call

You can direct the AWS SDK for Go to display the HTTP request and response it sends and receives for each call by including a configuration option when constructing the service client.

The following example uses the 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) }

// Create DynamoDB client

// and expose HTTP requests/responses

svc := dynamodb.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody)) // Add "CustomHeader" header with value of 10

svc.Handlers.Send.PushFront(func(r *request.Request) {

r.HTTPRequest.Header.Set("CustomHeader", fmt.Sprintf("%d", 10)) })

Service Operation Calls

// Call ListTables just to see HTTP request/response // The request should have the CustomHeader set to 10 _, _ = svc.ListTables(&dynamodb.ListTablesInput{}) }

If you run this program, the output should be similar to the following, where ACCESS-KEY is the access key of the user and TABLE-1, through TABLE-N are the names of the tables.

2017/10/25 11:10:57 DEBUG: Request dynamodb/ListTables Details:

---[ REQUEST POST-SIGN ]---POST / HTTP/1.1

Host: dynamodb.us-west-2.amazonaws.com

User-Agent: aws-sdk-go/1.10.34 (go1.8; windows; amd64) Content-Length: 2

Accept-Encoding: identity

Authorization: AWS4-HMAC-SHA256 Credential=ACCESS-KEY/20171025/us-west-2/dynamodb/

aws4_request, SignedHeaders=accept-encoding;content-length;content-type;host;x-amz-date;x-amz-target, Signature=9c92efe5d6c597cf29e4f7cc74de6dc2e39f8010a0d4957a397c59ef9cde21f2 Content-Type: application/x-amz-json-1.0

CustomHeader: 10

X-Amz-Date: 20171025T181057Z

X-Amz-Target: DynamoDB_20120810.ListTables

{}

---2017/10/25 11:10:58 DEBUG: Response dynamodb/ListTables Details:

---[ RESPONSE ]---HTTP/1.1 200 OK

Content-Length: 177 Connection: keep-alive

Content-Type: application/x-amz-json-1.0 Date: Wed, 25 Oct 2017 18:10:58 GMT Server: Server

X-Amz-Crc32: 3023160996

X-Amzn-Requestid: M5B4BM4UU569MVBSDG5O2O9ITJVV4KQNSO5AEMVJF66Q9ASUAAJG

---2017/10/25 11:10:58 {"TableNames":["TABLE-1","...","TABLE-N"]}

Service Operation Calls

You can call a service operation directly or with its request form. When you call a service operation, the SDK synchronously validates the input, builds the request, signs it with your credentials, sends it to AWS, and then gets a response or an error. In most cases, you can call service operations directly.

Calling Operations

Calling the operation will sync as the request is built, signed, sent, and the response is received. If an error occurs during the operation, it will be returned. The output or resulting structure won’t be valid.

For example, to call the Amazon S3 GET Object API, use the Amazon S3 service client instance and call its GetObject method:

result, err := s3Svc.GetObject(&s3.GetObjectInput{...}) // result is a *s3.GetObjectOutput struct pointer // err is a error which can be cast to awserr.Error.

Calling Operations with the Request Form

Passing Parameters to a Service Operation

When calling an operation on a service, you pass in input parameters as option values, similar to passing in a configuration. For example, to retrieve an object, you must specify a bucket and the object’s key by passing in the following parameters to the GetObject method:

svc := s3.New(session.New()) svc.GetObject(&s3.GetObjectInput{

Bucket: aws.String("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 Operations with the Request Form

Calling the request form of a service operation, which follows the naming pattern OperationName Request, provides a simple way to control when a request is built, signed, and sent. Calling the request form immediately returns a request object. The request object output is a struct pointer that is not valid until the request is sent and returned successfully.

Calling the request form can be useful when you want to construct a number of pre-signed requests, such as pre-signed Amazon S3 URLs. You can also use the request form to modify how the SDK sends a request.

The following example calls the request form of the GetObject method. The Send method signs the request before sending it.

req, result := s3Svc.GetObjectRequest(&s3.GetObjectInput{...})

// result is a *s3.GetObjectOutput struct pointer, not populated until req.Send() returns // req is a *aws.Request struct pointer. Used to Send request.

if err := req.Send(); err != nil { // process error

return }

// Process result

Handling Operation Response Body

Some API operations return a response struct that contain a Body field that is an io.ReadCloser. If you’re making requests with these operations, always be sure to call Close on the field.

resp, err := s3svc.GetObject(&s3.GetObjectInput{...}) if err != nil {

// handle error return

}

// Make sure to always close the response Body when finished defer resp.Body.Close()

decoder := json.NewDecoder(resp.Body)

if err := decoder.Decode(&myStruct); err != nil { // handle error

return

Concurrently Using Service Clients

}

Concurrently Using Service Clients

You can create goroutines that concurrently use the same service client to send multiple requests. You can use a service client with as many goroutines as you want. However, you cannot concurrently modify the service client’s configuration and request handlers. If you do, the service client operations might encounter race conditions. Define service client settings before you concurrently use it.

In the following example, an Amazon S3 service client is used in multiple goroutines. The example concurrently outputs all objects in 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.

sess, err := session.NewSession() if err != nil {

fmt.Println("Error creating session ", err) }var wg sync.WaitGroup

keysCh := make(chan string, 10) svc := s3.New(sess)

buckets := []string{"bucket1", "bucket2", "bucket3"}

for _, bucket := range buckets { params := &s3.ListObjectsInput{

Bucket: aws.String(bucket),

Bucket: aws.String(bucket),

在文檔中 AWS SDK for Go (version 1) (頁 21-200)

相關文件