Aws sdk go

Aws sdk go DEFAULT

Overview ▾

Package sdk is the official AWS SDK for the Go programming language.

The AWS SDK for Go provides APIs and utilities that developers can use to build Go applications that use AWS services, such as Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3).

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 on top of the AWS APIs that add additional capabilities and functionality. For example, the Amazon S3 Download and Upload Manager will automatically split up large objects into multiple parts and transfer them concurrently.

See the s3manager package documentation for more information. https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/

Getting More Information

Checkout the Getting Started Guide and API Reference Docs detailed the SDK's components and details on each AWS client the SDK supports.

The Getting Started Guide provides examples and detailed description of how to get setup with the SDK. https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html

The API Reference Docs include a detailed breakdown of the SDK's components such as utilities and AWS clients. Use this as a reference of the Go types included with the SDK, such as AWS clients, API operations, and API parameters. https://docs.aws.amazon.com/sdk-for-go/api/

Overview of SDK's Packages

The SDK is composed of two main components, SDK core, and service clients. The SDK core packages are all available under the aws package at the root of the SDK. Each client for a supported AWS service is available within its own package under the service folder at the root of the SDK.

* aws - SDK core, provides common shared types such as Config, Logger, and utilities to make working with API parameters easier. * awserr - Provides the error interface that the SDK will use for all errors that occur in the SDK's processing. This includes service API response errors as well. The Error type is made up of a code and message. Cast the SDK's returned error type to awserr.Error and call the Code method to compare returned error to specific error codes. See the package's documentation for additional values that can be extracted such as RequestId. * credentials - Provides the types and built in credentials providers the SDK will use to retrieve AWS credentials to make API requests with. Nested under this folder are also additional credentials providers such as stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. Use this to lookup AWS service endpoint information such as which services are in a region, and what regions a service is in. Constants are also provided for all region identifiers, e.g UsWest2RegionID for "us-west-2". * session - Provides initial default configuration, and load configuration from external sources such as environment and shared credentials file. * request - Provides the API request sending, and retry logic for the SDK. This package also includes utilities for defining your own request retryer, and configuring how the SDK processes the request. * service - Clients for AWS services. All services supported by the SDK are available under this folder.

How to Use the SDK's AWS Service Clients

The SDK includes the Go types and utilities you can use to make requests to AWS service APIs. Within the service folder at the root of the SDK you'll find a package for each AWS service the SDK supports. All service clients follows a common pattern of creation and usage.

When creating a client for an AWS service you'll first need to have a Session value constructed. The Session provides shared configuration that can be shared between your service clients. When service clients are created you can pass in additional configuration via the aws.Config type to override configuration provided by in the Session to create service client instances with custom configuration.

Once the service's client is created you can use it to make API requests the AWS service. These clients are safe to use concurrently.

Configuring the SDK

In the AWS SDK for Go, you can configure settings for service clients, such as the log level and maximum number of retries. Most settings are optional; however, for each service client, you must specify a region and your credentials. The SDK uses these values to send requests to the correct AWS region and sign requests with the correct credentials. You can specify these values as part of a session or as environment variables.

See the SDK's configuration guide for more information. https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html

See the session package documentation for more information on how to use Session with the SDK. https://docs.aws.amazon.com/sdk-for-go/api/aws/session/

See the Config type in the aws package for more information on configuration options. https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config

Configuring Credentials

When using the SDK you'll generally need your AWS credentials to authenticate with AWS services. The SDK supports multiple methods of supporting these credentials. By default the SDK will source credentials automatically from its default credential chain. See the session package for more information on this chain, and how to configure it. The common items in the credential chain are the following:

* Environment Credentials - Set of environment variables that are useful when sub processes are created for specific roles. * Shared Credentials file (~/.aws/credentials) - This file stores your credentials based on a profile name and is useful for local development. * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials to application running on an EC2 instance. This removes the need to manage credential files in production.

Credentials can be configured in code as well by setting the Config's Credentials value to a custom provider or using one of the providers included with the SDK to bypass the default credential chain and use a custom one. This is helpful when you want to instruct the SDK to only use a specific set of credentials or providers.

This example creates a credential provider for assuming an IAM role, "myRoleARN" and configures the S3 service client to use that role for API requests.

// Initial credentials loaded from SDK's default credential chain. Such as // the environment, shared credentials (~/.aws/credentials), or EC2 Instance // Role. These credentials will be used to to make the STS Assume Role API. sess := session.Must(session.NewSession()) // Create the credentials from AssumeRoleProvider to assume the role // referenced by the "myRoleARN" ARN. creds := stscreds.NewCredentials(sess, "myRoleArn") // Create service client value configured for credentials // from assumed role. svc := s3.New(sess, &aws.Config{Credentials: creds})/

See the credentials package documentation for more information on credential providers included with the SDK, and how to customize the SDK's usage of credentials. https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials

The SDK has support for the shared configuration file (~/.aws/config). This support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", or enabling the feature in code when creating a Session via the Option's SharedConfigState parameter.

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

Configuring AWS Region

In addition to the credentials you'll need to specify the region the SDK will use to make AWS API requests to. In the SDK you can specify the region either with an environment variable, or directly in code when a Session or service client is created. The last value specified in code wins if the region is specified multiple ways.

To set the region via the environment variable set the "AWS_REGION" to the region you want to the SDK to use. Using this method to set the region will allow you to run your application in multiple regions without needing additional code in the application to select the region.

AWS_REGION=us-west-2

The endpoints package includes constants for all regions the SDK knows. The values are all suffixed with RegionID. These values are helpful, because they reduce the need to type the region string manually.

To set the region on a Session use the aws package's Config struct parameter Region to the AWS region you want the service clients created from the session to use. This is helpful when you want to create multiple service clients, and all of the clients make API requests to the same region.

sess := session.Must(session.NewSession(&aws.Config{ Region: aws.String(endpoints.UsWest2RegionID), }))

See the endpoints package for the AWS Regions and Endpoints metadata. https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/

In addition to setting the region when creating a Session you can also set the region on a per service client bases. This overrides the region of a Session. This is helpful when you want to create service clients in specific regions different from the Session's region.

svc := s3.New(sess, &aws.Config{ Region: aws.String(endpoints.UsWest2RegionID), })

See the Config type in the aws package for more information and additional options such as setting the Endpoint, and other service client configuration options. https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config

Making API Requests

Once the client is created you can make an API request to the service. Each API method takes a input parameter, and returns the service response and an error. The SDK provides methods for making the API call in multiple ways.

In this list we'll use the S3 ListObjects API as an example for the different ways of making API requests.

* ListObjects - Base API operation that will make the API request to the service. * ListObjectsRequest - API methods suffixed with Request will construct the API request, but not send it. This is also helpful when you want to get a presigned URL for a request, and share the presigned URL instead of your application making the request directly. * ListObjectsPages - Same as the base API operation, but uses a callback to automatically handle pagination of the API's response. * ListObjectsWithContext - Same as base API operation, but adds support for the Context pattern. This is helpful for controlling the canceling of in flight requests. See the Go standard library context package for more information. This method also takes request package's Option functional options as the variadic argument for modifying how the request will be made, or extracting information from the raw HTTP response. * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for the Context pattern. Similar to ListObjectsWithContext this method also takes the request package's Option function option types as the variadic argument.

In addition to the API operations the SDK also includes several higher level methods that abstract checking for and waiting for an AWS resource to be in a desired state. In this list we'll use WaitUntilBucketExists to demonstrate the different forms of waiters.

* WaitUntilBucketExists. - Method to make API request to query an AWS service for a resource's state. Will return successfully when that state is accomplished. * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds support for the Context pattern. In addition these methods take request package's WaiterOptions to configure the waiter, and how underlying request will be made by the SDK.

The API method will document which error codes the service might return for the operation. These errors will also be available as const strings prefixed with "ErrCode" in the service client's package. If there are no errors listed in the API's SDK documentation you'll need to consult the AWS service's API documentation for the errors that could be returned.

ctx := context.Background() result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ Bucket: aws.String("my-bucket"), Key: aws.String("my-key"), }) if err != nil { // Cast err to awserr.Error to handle specific error codes. aerr, ok := err.(awserr.Error) if ok && aerr.Code() == s3.ErrCodeNoSuchKey { // Specific error code handling } return err } // Make sure to close the body when done with it for S3 GetObject APIs or // will leak connections. defer result.Body.Close() fmt.Println("Object Size:", aws.StringValue(result.ContentLength))

API Request Pagination and Resource Waiters

Pagination helper methods are suffixed with "Pages", and provide the functionality needed to round trip API page requests. Pagination methods take a callback function that will be called for each page of the API's response.

objects := []string{} err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ Bucket: aws.String(myBucket), }, func(p *s3.ListObjectsOutput, lastPage bool) bool { for _, o := range p.Contents { objects = append(objects, aws.StringValue(o.Key)) } return true // continue paging }) if err != nil { panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) } fmt.Println("Objects in bucket:", objects)

Waiter helper methods provide the functionality to wait for an AWS resource state. These methods abstract the logic needed to to check the state of an AWS resource, and wait until that resource is in a desired state. The waiter will block until the resource is in the state that is desired, an error occurs, or the waiter times out. If a resource times out the error code returned will be request.WaiterResourceNotReadyErrorCode.

err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ Bucket: aws.String(myBucket), }) if err != nil { aerr, ok := err.(awserr.Error) if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") } panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) } fmt.Println("Bucket", myBucket, "exists")

Complete SDK Example

This example shows a complete working Go file which will upload a file to S3 and use the Context pattern to implement timeout logic that will cancel the request if it takes too long. This example highlights how to use sessions, create a service client, make a request, handle the error, and process the response.

package main import ( "context" "flag" "fmt" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) // Uploads a file to S3 given a bucket and object key. Also takes a duration // value to terminate the update if it doesn't complete within that time. // // The AWS Region needs to be provided in the AWS shared config or on the // environment variable as `AWS_REGION`. Credentials also must be provided // Will default to shared config file, but can load from environment if provided. // // Usage: // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt func main() { var bucket, key string var timeout time.Duration flag.StringVar(&bucket, "b", "", "Bucket name.") flag.StringVar(&key, "k", "", "Object key name.") flag.DurationVar(&timeout, "d", 0, "Upload timeout.") flag.Parse() // All clients require a Session. The Session provides the client with // shared configuration such as region, endpoint, and credentials. A // Session should be shared where possible to take advantage of // configuration and credential caching. See the session package for // more information. sess := session.Must(session.NewSession()) // Create a new instance of the service's client with a Session. // Optional aws.Config values can also be provided as variadic arguments // to the New function. This option allows you to provide service // specific configuration. svc := s3.New(sess) // Create a context with a timeout that will abort the upload if it takes // more than the passed in timeout. ctx := context.Background() var cancelFn func() if timeout > 0 { ctx, cancelFn = context.WithTimeout(ctx, timeout) } // Ensure the context is canceled to prevent leaking. // See context package for more information, https://golang.org/pkg/context/ defer cancelFn() // Uploads the object to S3. The Context will interrupt the request if the // timeout expires. _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ Bucket: aws.String(bucket), Key: aws.String(key), Body: os.Stdin, }) if err != nil { if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { // If the SDK can determine the request or retry delay was canceled // by a context the CanceledErrorCode error code will be returned. fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) } else { fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) } os.Exit(1) } fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) }
Sours: https://docs.aws.amazon.com/sdk-for-go/api/

AWS SDK for Go

API ReferenceBuild statusApache V2 License

aws-sdk-go is the official AWS SDK for the Go programming language.

Checkout our release notes for information about the latest bug fixes, updates, and features added to the SDK.

We announced the General Availability for the AWS SDK for Go V2 (v2). The v2 SDK source is available at https://github.com/aws/aws-sdk-go-v2. Review the v2 SDK's Developer Guide to get started with AWS SDK for Go V2 or review the migration guide if you already use version 1.

Jump To:

Getting Started

Installing

Use to retrieve the SDK to add it to your workspace, or project's Go module dependencies.

To update the SDK use to retrieve the latest version of the SDK.

Dependencies

The SDK includes a folder containing the runtime dependencies of the SDK. The metadata of the SDK's dependencies can be found in the Go module file or Dep file .

Go Modules

If you are using Go modules, your will default to the latest tagged release version of the SDK. To get a specific release version of the SDK use in your command.

To get the latest SDK repository change use .

Go 1.5

If you are using Go 1.5 without vendoring enabled, (), you will need to use when retrieving the SDK to get its dependencies.

This will still include the folder. The folder can be deleted if not used by your environment.

Quick Examples

Complete SDK Example

This example shows a complete working Go file which will upload a file to S3 and use the Context pattern to implement timeout logic that will cancel the request if it takes too long. This example highlights how to use sessions, create a service client, make a request, handle the error, and process the response.

Overview of SDK's Packages

The SDK is composed of two main components, SDK core, and service clients. The SDK core packages are all available under the aws package at the root of the SDK. Each client for a supported AWS service is available within its own package under the service folder at the root of the SDK.

  • aws - SDK core, provides common shared types such as Config, Logger, and utilities to make working with API parameters easier.

    • awserr - Provides the error interface that the SDK will use for all errors that occur in the SDK's processing. This includes service API response errors as well. The Error type is made up of a code and message. Cast the SDK's returned error type to awserr.Error and call the Code method to compare returned error to specific error codes. See the package's documentation for additional values that can be extracted such as RequestID.

    • credentials - Provides the types and built in credentials providers the SDK will use to retrieve AWS credentials to make API requests with. Nested under this folder are also additional credentials providers such as stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles.

    • endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. Use this to lookup AWS service endpoint information such as which services are in a region, and what regions a service is in. Constants are also provided for all region identifiers, e.g UsWest2RegionID for "us-west-2".

    • session - Provides initial default configuration, and load configuration from external sources such as environment and shared credentials file.

    • request - Provides the API request sending, and retry logic for the SDK. This package also includes utilities for defining your own request retryer, and configuring how the SDK processes the request.

  • service - Clients for AWS services. All services supported by the SDK are available under this folder.

How to Use the SDK's AWS Service Clients

The SDK includes the Go types and utilities you can use to make requests to AWS service APIs. Within the service folder at the root of the SDK you'll find a package for each AWS service the SDK supports. All service clients follow common pattern of creation and usage.

When creating a client for an AWS service you'll first need to have a Session value constructed. The Session provides shared configuration that can be shared between your service clients. When service clients are created you can pass in additional configuration via the aws.Config type to override configuration provided by in the Session to create service client instances with custom configuration.

Once the service's client is created you can use it to make API requests the AWS service. These clients are safe to use concurrently.

Configuring the SDK

In the AWS SDK for Go, you can configure settings for service clients, such as the log level and maximum number of retries. Most settings are optional; however, for each service client, you must specify a region and your credentials. The SDK uses these values to send requests to the correct AWS region and sign requests with the correct credentials. You can specify these values as part of a session or as environment variables.

See the SDK's configuration guide for more information.

See the session package documentation for more information on how to use Session with the SDK.

See the Config type in the aws package for more information on configuration options.

Configuring Credentials

When using the SDK you'll generally need your AWS credentials to authenticate with AWS services. The SDK supports multiple methods of supporting these credentials. By default the SDK will source credentials automatically from its default credential chain. See the session package for more information on this chain, and how to configure it. The common items in the credential chain are the following:

  • Environment Credentials - Set of environment variables that are useful when sub processes are created for specific roles.

  • Shared Credentials file (~/.aws/credentials) - This file stores your credentials based on a profile name and is useful for local development.

  • EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials to application running on an EC2 instance. This removes the need to manage credential files in production.

Credentials can be configured in code as well by setting the Config's Credentials value to a custom provider or using one of the providers included with the SDK to bypass the default credential chain and use a custom one. This is helpful when you want to instruct the SDK to only use a specific set of credentials or providers.

This example creates a credential provider for assuming an IAM role, "myRoleARN" and configures the S3 service client to use that role for API requests.

See the credentials package documentation for more information on credential providers included with the SDK, and how to customize the SDK's usage of credentials.

The SDK has support for the shared configuration file (~/.aws/config). This support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", or enabling the feature in code when creating a Session via the Option's SharedConfigState parameter.

Configuring AWS Region

In addition to the credentials you'll need to specify the region the SDK will use to make AWS API requests to. In the SDK you can specify the region either with an environment variable, or directly in code when a Session or service client is created. The last value specified in code wins if the region is specified multiple ways.

To set the region via the environment variable set the "AWS_REGION" to the region you want to the SDK to use. Using this method to set the region will allow you to run your application in multiple regions without needing additional code in the application to select the region.

The endpoints package includes constants for all regions the SDK knows. The values are all suffixed with RegionID. These values are helpful, because they reduce the need to type the region string manually.

To set the region on a Session use the aws package's Config struct parameter Region to the AWS region you want the service clients created from the session to use. This is helpful when you want to create multiple service clients, and all of the clients make API requests to the same region.

See the endpoints package for the AWS Regions and Endpoints metadata.

In addition to setting the region when creating a Session you can also set the region on a per service client bases. This overrides the region of a Session. This is helpful when you want to create service clients in specific regions different from the Session's region.

See the Config type in the aws package for more information and additional options such as setting the Endpoint, and other service client configuration options.

Making API Requests

Once the client is created you can make an API request to the service. Each API method takes a input parameter, and returns the service response and an error. The SDK provides methods for making the API call in multiple ways.

In this list we'll use the S3 ListObjects API as an example for the different ways of making API requests.

  • ListObjects - Base API operation that will make the API request to the service.

  • ListObjectsRequest - API methods suffixed with Request will construct the API request, but not send it. This is also helpful when you want to get a presigned URL for a request, and share the presigned URL instead of your application making the request directly.

  • ListObjectsPages - Same as the base API operation, but uses a callback to automatically handle pagination of the API's response.

  • ListObjectsWithContext - Same as base API operation, but adds support for the Context pattern. This is helpful for controlling the canceling of in flight requests. See the Go standard library context package for more information. This method also takes request package's Option functional options as the variadic argument for modifying how the request will be made, or extracting information from the raw HTTP response.

  • ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for the Context pattern. Similar to ListObjectsWithContext this method also takes the request package's Option function option types as the variadic argument.

In addition to the API operations the SDK also includes several higher level methods that abstract checking for and waiting for an AWS resource to be in a desired state. In this list we'll use WaitUntilBucketExists to demonstrate the different forms of waiters.

  • WaitUntilBucketExists. - Method to make API request to query an AWS service for a resource's state. Will return successfully when that state is accomplished.

  • WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds support for the Context pattern. In addition these methods take request package's WaiterOptions to configure the waiter, and how underlying request will be made by the SDK.

The API method will document which error codes the service might return for the operation. These errors will also be available as const strings prefixed with "ErrCode" in the service client's package. If there are no errors listed in the API's SDK documentation you'll need to consult the AWS service's API documentation for the errors that could be returned.

API Request Pagination and Resource Waiters

Pagination helper methods are suffixed with "Pages", and provide the functionality needed to round trip API page requests. Pagination methods take a callback function that will be called for each page of the API's response.

Waiter helper methods provide the functionality to wait for an AWS resource state. These methods abstract the logic needed to check the state of an AWS resource, and wait until that resource is in a desired state. The waiter will block until the resource is in the state that is desired, an error occurs, or the waiter times out. If a resource times out the error code returned will be request.WaiterResourceNotReadyErrorCode.

Getting Help

Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests.

This SDK implements AWS service APIs. For general issues regarding the AWS services and their limitations, you may also take a look at the Amazon Web Services Discussion Forums.

Opening Issues

If you encounter a bug with the AWS SDK for Go we would like to hear about it. Search the existing issues and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS SDK for Go, Go language, and OS you’re using. Please also include reproduction case when appropriate.

The GitHub issues are intended for bug reports and feature requests. For help and questions with using AWS SDK for Go please make use of the resources listed in the Getting Help section. Keeping the list of open issues lean will help us respond in a timely manner.

Contributing

We work hard to provide a high-quality and useful SDK for our AWS services, and we greatly value feedback and contributions from our community. Please review our contributing guidelines before submitting any issues or pull requests to ensure we have all the necessary information to effectively respond to your bug report or contribution.

Maintenance and support for SDK major versions

For information about maintenance and support for SDK major versions and our underlying dependencies, see the following in the AWS SDKs and Tools Shared Configuration and Credentials Reference Guide:

Resources

Developer guide - This document is a general introduction on how to configure and make requests with the SDK. If this is your first time using the SDK, this documentation and the API documentation will help you get started. This document focuses on the syntax and behavior of the SDK. The Service Developer Guide will help you get started using specific AWS services.

SDK API Reference Documentation - Use this document to look up all API operation input and output parameters for AWS services supported by the SDK. The API reference also includes documentation of the SDK, and examples how to using the SDK, service client API operations, and API operation require parameters.

Service Documentation - Use this documentation to learn how to interface with AWS services. These guides are great for getting started with a service, or when looking for more information about a service. While this document is not required for coding, services may supply helpful samples to look out for.

SDK Examples - Included in the SDK's repo are several hand crafted examples using the SDK features and AWS services.

Forum - Ask questions, get help, and give feedback

Issues - Report issues, submit pull requests, and get involved (see Apache 2.0 License)

Sours: https://pkg.go.dev/github.com/aws/aws-sdk-go
  1. Custom cuff.co review
  2. Offset box wrenches
  3. Spud gun metal

Package aws provides the core SDK's utilities and shared types. Use this package's utilities to simplify setting and reading API operations parameters.

Value and Pointer Conversion Utilities ¶

This package includes a helper conversion utility for each scalar type the SDK's API use. These utilities make getting a pointer of the scalar, and dereferencing a pointer easier.

Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. The Pointer to value will safely dereference the pointer and return its value. If the pointer was nil, the scalar's zero value will be returned.

The value to pointer functions will be named after the scalar type. So get a *string from a string value use the "String" function. This makes it easy to to get pointer of a literal string value, because getting the address of a literal requires assigning the value to a variable first.

var strPtr *string // Without the SDK's conversion functions str := "my string" strPtr = &str // With the SDK's conversion functions strPtr = aws.String("my string") // Convert *string to string value str = aws.StringValue(strPtr)

In addition to scalars the aws package also includes conversion utilities for map and slice for commonly types used in API parameters. The map and slice conversion functions use similar naming pattern as the scalar conversion functions.

var strPtrs []*string var strs []string = []string{"Go", "Gophers", "Go"} // Convert []string to []*string strPtrs = aws.StringSlice(strs) // Convert []*string to []string strs = aws.StringValueSlice(strPtrs)

SDK Default HTTP Client ¶

The SDK will use the http.DefaultClient if a HTTP client is not provided to the SDK's Session, or service client constructor. This means that if the http.DefaultClient is modified by other components of your application the modifications will be picked up by the SDK as well.

In some cases this might be intended, but it is a better practice to create a custom HTTP Client to share explicitly through your application. You can configure the SDK to use the custom HTTP Client by setting the HTTPClient value of the SDK's Config type when creating a Session or service client.

Package aws provides core functionality for making requests to AWS services.

Bool returns a pointer to the bool value passed in.

BoolMap converts a string map of bool values into a string map of bool pointers

BoolSlice converts a slice of bool values into a slice of bool pointers

BoolValue returns the value of the bool pointer passed in or false if the pointer is nil.

BoolValueMap converts a string map of bool pointers into a string map of bool values

BoolValueSlice converts a slice of bool pointers into a slice of bool values

Float32 returns a pointer to the float32 value passed in.

Float32Map converts a string map of float32 values into a string map of float32 pointers

Float32Slice converts a slice of float32 values into a slice of float32 pointers

Float32Value returns the value of the float32 pointer passed in or 0 if the pointer is nil.

Float32ValueMap converts a string map of float32 pointers into a string map of float32 values

Float32ValueSlice converts a slice of float32 pointers into a slice of float32 values

Float64 returns a pointer to the float64 value passed in.

Float64Map converts a string map of float64 values into a string map of float64 pointers

Float64Slice converts a slice of float64 values into a slice of float64 pointers

Float64Value returns the value of the float64 pointer passed in or 0 if the pointer is nil.

Float64ValueMap converts a string map of float64 pointers into a string map of float64 values

Float64ValueSlice converts a slice of float64 pointers into a slice of float64 values

Int returns a pointer to the int value passed in.

Int16 returns a pointer to the int16 value passed in.

Int16Map converts a string map of int16 values into a string map of int16 pointers

Int16Slice converts a slice of int16 values into a slice of int16 pointers

Int16Value returns the value of the int16 pointer passed in or 0 if the pointer is nil.

Int16ValueMap converts a string map of int16 pointers into a string map of int16 values

Int16ValueSlice converts a slice of int16 pointers into a slice of int16 values

Int32 returns a pointer to the int32 value passed in.

Int32Map converts a string map of int32 values into a string map of int32 pointers

Int32Slice converts a slice of int32 values into a slice of int32 pointers

Int32Value returns the value of the int32 pointer passed in or 0 if the pointer is nil.

Int32ValueMap converts a string map of int32 pointers into a string map of int32 values

Int32ValueSlice converts a slice of int32 pointers into a slice of int32 values

Int64 returns a pointer to the int64 value passed in.

Int64Map converts a string map of int64 values into a string map of int64 pointers

Int64Slice converts a slice of int64 values into a slice of int64 pointers

Int64Value returns the value of the int64 pointer passed in or 0 if the pointer is nil.

Int64ValueMap converts a string map of int64 pointers into a string map of int64 values

Int64ValueSlice converts a slice of int64 pointers into a slice of int64 values

Int8 returns a pointer to the int8 value passed in.

Int8Map converts a string map of int8 values into a string map of int8 pointers

Int8Slice converts a slice of int8 values into a slice of int8 pointers

Int8Value returns the value of the int8 pointer passed in or 0 if the pointer is nil.

Int8ValueMap converts a string map of int8 pointers into a string map of int8 values

Int8ValueSlice converts a slice of int8 pointers into a slice of int8 values

IntMap converts a string map of int values into a string map of int pointers

func IntSlice(src []int) []*int

IntSlice converts a slice of int values into a slice of int pointers

IntValue returns the value of the int pointer passed in or 0 if the pointer is nil.

IntValueMap converts a string map of int pointers into a string map of int values

func IntValueSlice(src []*int) []int

IntValueSlice converts a slice of int pointers into a slice of int values

IsReaderSeekable returns if the underlying reader type can be seeked. A io.Reader might not actually be seekable if it is the ReaderSeekerCloser type.

MillisecondsTimeValue converts an int64 pointer to a time.Time value representing milliseconds sinch Epoch or time.Time{} if the pointer is nil.

SecondsTimeValue converts an int64 pointer to a time.Time value representing seconds since Epoch or time.Time{} if the pointer is nil.

SeekerLen attempts to get the number of bytes remaining at the seeker's current position. Returns the number of bytes remaining or error.

SleepWithContext will wait for the timer duration to expire, or the context is canceled. Which ever happens first. If the context is canceled the Context's error will be returned.

Expects Context to always return a non-nil error if the Done channel is closed.

String returns a pointer to the string value passed in.

StringMap converts a string map of string values into a string map of string pointers

StringSlice converts a slice of string values into a slice of string pointers

StringValue returns the value of the string pointer passed in or "" if the pointer is nil.

StringValueMap converts a string map of string pointers into a string map of string values

StringValueSlice converts a slice of string pointers into a slice of string values

Time returns a pointer to the time.Time value passed in.

TimeMap converts a string map of time.Time values into a string map of time.Time pointers

TimeSlice converts a slice of time.Time values into a slice of time.Time pointers

TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". The result is undefined if the Unix time cannot be represented by an int64. Which includes calling TimeUnixMilli on a zero Time is undefined.

This utility is useful for service API's such as CloudWatch Logs which require their unix time values to be in milliseconds.

See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information.

TimeValue returns the value of the time.Time pointer passed in or time.Time{} if the pointer is nil.

TimeValueMap converts a string map of time.Time pointers into a string map of time.Time values

TimeValueSlice converts a slice of time.Time pointers into a slice of time.Time values

URLHostname will extract the Hostname without port from the URL value.

Wrapper of net/url#URL.Hostname for backwards Go version compatibility.

Uint returns a pointer to the uint value passed in.

Uint16 returns a pointer to the uint16 value passed in.

Uint16Map converts a string map of uint16 values into a string map of uint16 pointers

Uint16Slice converts a slice of uint16 values into a slice of uint16 pointers

Uint16Value returns the value of the uint16 pointer passed in or 0 if the pointer is nil.

Uint16ValueMap converts a string map of uint16 pointers into a string map of uint16 values

Uint16ValueSlice converts a slice of uint16 pointers into a slice of uint16 values

Uint32 returns a pointer to the uint32 value passed in.

Uint32Map converts a string map of uint32 values into a string map of uint32 pointers

Uint32Slice converts a slice of uint32 values into a slice of uint32 pointers

Uint32Value returns the value of the uint32 pointer passed in or 0 if the pointer is nil.

Uint32ValueMap converts a string map of uint32 pointers into a string map of uint32 values

Uint32ValueSlice converts a slice of uint32 pointers into a slice of uint32 values

Uint64 returns a pointer to the uint64 value passed in.

Uint64Map converts a string map of uint64 values into a string map of uint64 pointers

Uint64Slice converts a slice of uint64 values into a slice of uint64 pointers

Uint64Value returns the value of the uint64 pointer passed in or 0 if the pointer is nil.

Uint64ValueMap converts a string map of uint64 pointers into a string map of uint64 values

Uint64ValueSlice converts a slice of uint64 pointers into a slice of uint64 values

Uint8 returns a pointer to the uint8 value passed in.

Uint8Map converts a string map of uint8 values into a string map of uint8 pointers

Uint8Slice converts a slice of uint8 values into a slice of uint8 pointers

Uint8Value returns the value of the uint8 pointer passed in or 0 if the pointer is nil.

Uint8ValueMap converts a string map of uint8 pointers into a string map of uint8 values

Uint8ValueSlice converts a slice of uint8 pointers into a slice of uint8 values

UintMap converts a string map of uint values uinto a string map of uint pointers

UintSlice converts a slice of uint values uinto a slice of uint pointers

UintValue returns the value of the uint pointer passed in or 0 if the pointer is nil.

UintValueMap converts a string map of uint pointers uinto a string map of uint values

UintValueSlice converts a slice of uint pointers uinto a slice of uint values

Sours: https://pkg.go.dev/github.com/aws/aws-sdk-go/aws
AWS SDK for Go - Gophers Meetup

Getting Started with the AWS SDK for Go

The AWS SDK for Go requires Go 1.5 or later. You can view your current version of Go by running the command. For information about installing or upgrading your version of Go, see https://golang.org/doc/install.

Get an Amazon Account

Before you can use the AWS SDK for Go, you must have an Amazon account. See How do I create and activate a new Amazon Web Services account? for details.

Install the AWS SDK for Go

To install the SDK and its dependencies, run the following Go command.

If you set the Go vendor experiment environment variable to , you can use the following command to get the SDK. The SDK’s runtime dependencies are vendored in the folder.

Get your AWS access keys

Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS. If you don’t have access keys, you can create them by using the AWS Management Console. We recommend that you use IAM access keys instead of AWS root account access keys. IAM lets you securely control access to AWS services and resources in your AWS account.

To get your access key ID and secret access key

  1. Open the IAM console.

  2. On the navigation menu, choose Users.

  3. Choose your IAM user name (not the check box).

  4. Open the Security credentials tab, and then choose Create access key.

  5. To see the new access key, choose Show. Your credentials resemble the following:

    • Access key ID:

    • Secret access key:

  6. To download the key pair, choose Download .csv file. Store the keys

in a secure location.

Important

Keep the keys confidential to protect your AWS account, and never email them. Do not share them outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one who legitimately represents Amazon will ever ask you for your secret key.

Related topics

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:

Sours: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/setting-up.html

Sdk go aws

AWS SDK for Go Code Examples

The AWS SDK for Go examples can help you write your own Go applications that use Amazon Web Services. The examples assume you have already set up and configured the SDK (that is, you have imported all required packages and set your credentials and region). For more information, see Getting Started with the AWS SDK for Go and Configuring the AWS SDK for Go.

Find the source code for these examples and others in the AWS documentation code examples repository on GitHub. To propose a new code example for the AWS documentation team to consider producing, create a new request. The team is looking to produce code examples that cover broader scenarios and use cases, versus simple code snippets that cover only individual API calls. For instructions, see the Proposing new code examples section in the Readme on GitHub.

Sours: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/common-examples.html
Introduction to AWS Lambda using Golang

AWS SDK for Go Developer Guide

Welcome to the AWS SDK for Go. The AWS SDK for Go provides APIs and utilities that developers can use to build Go applications that use AWS services, such as Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3).

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.

Using the AWS SDK for Go with AWS Cloud9

AWS Cloud9 is a web-based integrated development environment (IDE) that contains a collection of tools that you use to code, build, run, test, debug, and release software in the cloud.

See Using AWS Cloud9 with the AWS SDK for Go for information on using AWS Cloud9 with the AWS SDK for Go.

More Info

Maintenance and support for SDK major versions

For information about maintenance and support for SDK major versions and their underlying dependencies, see the following in the AWS SDKs and Tools Reference Guide:

Sours: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html

Similar news:

Getting Started with the AWS SDK for Go V2

The AWS SDK for Go requires Go 1.15 or later. You can view your current version of Go by running the following command.

For information about installing or upgrading your version of Go, see https://golang.org/doc/install.

Get an Amazon Account

Before you can use the AWS SDK for Go V2, you must have an Amazon account. See How do I create and activate a new AWS account? for details.

Install the AWS SDK for Go V2

The AWS SDK for Go V2 uses Go Modules, which was a feature introduced in Go 1.11. To get started initialize your local project by running the following Go command.

After initializing your Go Module project you will be able to retrieve the SDK, and its required dependencies using the command. These dependencies will be recorded in the file which was created by the previous command.

The following commands show how to retrieve the standard set of SDK modules to use in your application.

This will retrieve the core SDK module, and the config module which is used for loading the AWS shared configuration.

Next you can install one or more AWS service API clients required by your application. All API clients are located under import hierarchy. A complete set of currently supported API clients can be found here. To install a service client, execute the following command to retrieve the module and record the dependency in your file. In this example we retrieve the Amazon S3 API client.

Get your AWS access keys

Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS. If you don’t have access keys, you can create them by using the AWS Management Console. We recommend that you use IAM access keys instead of AWS root account access keys. IAM lets you securely control access to AWS services and resources in your AWS account. Note

To create access keys, you must have permissions to perform the required IAM actions. For more information, see Granting IAM User Permission to Manage Password Policy and Credentials in the IAM User Guide.

To get your access key ID and secret access key.

  1. Open the IAM console
  2. On the navigation menu, choose Users.
  3. Choose your IAM user name (not the check box).
  4. Open the Security credentials tab, and then choose Create access key.
  5. To see the new access key, choose Show. Your credentials resemble the following:
    • Access key ID:
    • Secret access key:
  6. To download the key pair, choose Download .csv file. Store the keys in a secure location.

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

Invoke an Operation

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, Config, and Amazon S3 libraries. After importing the SDK packages, the AWS SDK Shared Configuration is loaded, a client is constructed, and an API operation is invoked.

Last modified August 4, 2021: Typo in getting-started.md (#1365) (95b48d1)

Sours: https://aws.github.io/aws-sdk-go-v2/docs/getting-started/


138 139 140 141 142