AWS SDK for Go v2 with 130+ service clients, Request/Send pattern, and context support.
aws)Import: github.com/aws/aws-sdk-go-v2/aws
The aws package provides the foundational types, utilities, and infrastructure used by all service clients.
Service configuration shared by all service clients.
type Config struct {
// AWS region (required for most services)
Region string
// Credentials provider for signing requests
Credentials CredentialsProvider
// Custom endpoint resolver (overrides default service endpoints)
EndpointResolver EndpointResolver
// Custom HTTP client (defaults to http.DefaultClient)
HTTPClient *http.Client
// Request handler chain
Handlers Handlers
// Retry configuration
Retryer Retryer
// Logging level (default: LogOff)
LogLevel LogLevel
// Logger implementation
Logger Logger
// Force ShouldRetry check even when Retryable is already set
EnforceShouldRetryCheck bool
// Disable URL path cleaning for REST protocol requests (e.g., S3 empty dir names)
DisableRestProtocolURICleaning bool
}
func NewConfig() *Config
func (c Config) Copy() Configcfg := aws.NewConfig()
// Copy with modifications
cfg2 := cfg.Copy()
cfg2.Region = "eu-west-1"type Credentials struct {
AccessKeyID string
SecretAccessKey string
SessionToken string // empty for non-temporary credentials
Source string // name of the provider
CanExpire bool
Expires time.Time
}
func (v Credentials) Expired() bool
func (v Credentials) HasKeys() booltype CredentialsProvider interface {
Retrieve() (Credentials, error)
IsExpired() bool
}Non-expiring credentials set programmatically.
const StaticCredentialsProviderName = "StaticCredentialsProvider"
type StaticCredentialsProvider struct {
Value Credentials
}
func NewStaticCredentialsProvider(key, secret, session string) StaticCredentialsProvider
func (s StaticCredentialsProvider) Retrieve() (Credentials, error)
func (s StaticCredentialsProvider) IsExpired() boolcreds := aws.NewStaticCredentialsProvider("AKID", "SECRET", "")
cfg.Credentials = credsThread-safe credentials caching wrapper.
type SafeCredentialsProvider struct {
RetrieveFn func() (Credentials, error)
// unexported fields
}
func (p *SafeCredentialsProvider) Retrieve() (Credentials, error)
func (p *SafeCredentialsProvider) Invalidate()Searches a chain of providers for the first valid credentials.
type ChainProvider struct {
SafeCredentialsProvider
Providers []CredentialsProvider
}
func NewChainProvider(providers []CredentialsProvider) *ChainProviderUse for unsigned requests (e.g., public S3 buckets).
var AnonymousCredentials = StaticCredentialsProvider{
Value: Credentials{Source: "AnonymousCredentials"},
}s3Cfg := cfg.Copy()
s3Cfg.Credentials = aws.AnonymousCredentials
svc := s3.New(s3Cfg)var ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil)
var NeverExpire = time.Unix(math.MaxInt64, 0)type Endpoint struct {
URL string
SigningName string
SigningRegion string
SigningNameDerived bool
SigningMethod string
}
type EndpointResolver interface {
ResolveEndpoint(service, region string) (Endpoint, error)
}
// Wrap a function as EndpointResolver
type EndpointResolverFunc func(service, region string) (Endpoint, error)
func (fn EndpointResolverFunc) ResolveEndpoint(service, region string) (Endpoint, error)
// Static endpoint
type ResolveWithEndpoint Endpoint
func ResolveWithEndpointURL(url string) ResolveWithEndpoint
func (v ResolveWithEndpoint) ResolveEndpoint(service, region string) (Endpoint, error)// Use local endpoint (e.g., LocalStack)
cfg.EndpointResolver = aws.ResolveWithEndpointURL("http://localhost:4566")
// Custom resolver with fallback
cfg.EndpointResolver = aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {
if service == endpoints.S3ServiceID {
return aws.Endpoint{URL: "https://my-s3-proxy.example.com"}, nil
}
return endpoints.NewDefaultResolver().ResolveEndpoint(service, region)
})The Request is the core request type. Service clients create requests using New<Operation>Request() methods. Normally you work with the typed request wrappers returned by service clients, not aws.Request directly.
type Request struct {
Config Config
Metadata Metadata
Handlers Handlers
Retryer
Time time.Time
ExpireTime time.Duration
Operation *Operation
HTTPRequest *http.Request
HTTPResponse *http.Response
Body io.ReadSeeker
Params interface{}
Error error
Data interface{}
RequestID string
RetryCount int
Retryable *bool
RetryDelay time.Duration
NotHoist bool
SignedHeaderVals http.Header
LastSignedAt time.Time
DisableFollowRedirects bool
}
func (r *Request) Send() error
func (r *Request) Sign() error
func (r *Request) SetContext(ctx Context)
func (r *Request) Presign(expireTime time.Duration) (string, error)
func (r *Request) PresignRequest(expireTime time.Duration) (string, http.Header, error)
func (r *Request) SetBufferBody(buf []byte)
func (r *Request) SetStringBody(s string)
func (r *Request) SetReaderBody(reader io.ReadSeeker)
func (r *Request) ResetBody()
func (r *Request) ParamsFilled() bool
func (r *Request) WillRetry() bool
func (r *Request) IsErrorExpired() bool
func (r *Request) IsErrorRetryable() bool
func (r *Request) IsErrorThrottle() bool
func (r *Request) GetBody() io.ReadSeekerDescribes an API operation.
type Operation struct {
Name string
HTTPMethod string
HTTPPath string
*Paginator
BeforePresignFn func(r *Request) error
}
type Paginator struct {
InputTokens []string
OutputTokens []string
LimitToken string
TruncationToken string
}General pagination type. Service clients expose typed Paginate() methods.
type Pager struct {
NewRequest func() (*Request, error)
// unexported fields
}
func (p *Pager) Next() bool
func (p *Pager) CurrentPage() interface{}
func (p *Pager) Err() errorBase client embedded in all service client types.
type Client struct {
Metadata Metadata
Config Config
Region string
Credentials CredentialsProvider
EndpointResolver EndpointResolver
Handlers Handlers
Retryer Retryer
LogLevel LogLevel
Logger Logger
HTTPClient *http.Client
}
type Metadata struct {
ServiceName string
APIVersion string
Endpoint string
SigningName string
SigningRegion string
JSONVersion string
TargetPrefix string
}
func NewClient(cfg Config, metadata Metadata) *Client
func (c *Client) NewRequest(operation *Operation, params interface{}, data interface{}) *RequestRequest lifecycle hooks.
type Handlers struct {
Validate HandlerList
Build HandlerList
Sign HandlerList
Send HandlerList
ValidateResponse HandlerList
Unmarshal HandlerList
UnmarshalMeta HandlerList
UnmarshalError HandlerList
Retry HandlerList
AfterRetry HandlerList
Complete HandlerList
}
func (h *Handlers) Copy() Handlers
func (h *Handlers) Clear()
type HandlerList struct {
AfterEachFn func(item HandlerListRunItem) bool
// unexported fields
}
func (l *HandlerList) PushBack(f func(*Request))
func (l *HandlerList) PushFront(f func(*Request))
func (l *HandlerList) PushBackNamed(n NamedHandler)
func (l *HandlerList) PushFrontNamed(n NamedHandler)
func (l *HandlerList) Remove(n NamedHandler)
func (l *HandlerList) RemoveByName(name string)
func (l *HandlerList) Run(r *Request)
func (l *HandlerList) Clear()
func (l *HandlerList) Len() int
type NamedHandler struct {
Name string
Fn func(*Request)
}
type HandlerListRunItem struct {
Index int
Handler NamedHandler
Request *Request
}
func HandlerListLogItem(item HandlerListRunItem) bool
func HandlerListStopOnError(item HandlerListRunItem) booltype Retryer interface {
RetryRules(*Request) time.Duration
ShouldRetry(*Request) bool
MaxRetries() int
}
// Default implementation with exponential backoff
type DefaultRetryer struct {
NumMaxRetries int
}Wait for a resource to reach a desired state.
type Waiter struct {
Name string
Acceptors []WaiterAcceptor
Logger Logger
MaxAttempts int
Delay WaiterDelay
RequestOptions []Option
NewRequest func([]Option) (*Request, error)
SleepWithContext func(Context, time.Duration) error
}
func (w *Waiter) ApplyOptions(opts ...WaiterOption)
func (w Waiter) WaitWithContext(ctx Context) error
type WaiterAcceptor struct {
State WaiterState
Matcher WaiterMatchMode
Argument string
Expected interface{}
}
type WaiterDelay func(attempt int) time.Duration
func ConstantWaiterDelay(delay time.Duration) WaiterDelay
type WaiterState int
const (
SuccessWaiterState WaiterState = iota
FailureWaiterState
RetryWaiterState
)
type WaiterMatchMode int
const (
PathAllWaiterMatch WaiterMatchMode = iota
PathWaiterMatch
PathAnyWaiterMatch
PathListWaiterMatch
StatusWaiterMatch
ErrorWaiterMatch
)
type WaiterOption func(*Waiter)
func WithWaiterDelay(delayer WaiterDelay) WaiterOption
func WithWaiterLogger(logger Logger) WaiterOption
func WithWaiterMaxAttempts(max int) WaiterOption
func WithWaiterRequestOptions(opts ...Option) WaiterOption
func (m WaiterMatchMode) String() string
func (s WaiterState) String() stringtype LogLevel uint
const (
LogOff LogLevel = iota * 0x1000
LogDebug
)
// Debug sub-levels (combine with LogDebug using |)
const (
LogDebugWithSigning LogLevel = LogDebug | (1 << iota)
LogDebugWithHTTPBody
LogDebugWithRequestRetries
LogDebugWithRequestErrors
)
func (l LogLevel) Matches(v LogLevel) bool
func (l LogLevel) AtLeast(v LogLevel) bool
type Logger interface {
Log(...interface{})
}
type LoggerFunc func(...interface{})
func (f LoggerFunc) Log(args ...interface{})
func NewDefaultLogger() LoggerConverting between value types and pointer types for API input/output fields.
// string
func String(v string) *string
func StringValue(v *string) string
func StringSlice(src []string) []*string
func StringValueSlice(src []*string) []string
func StringMap(src map[string]string) map[string]*string
func StringValueMap(src map[string]*string) map[string]string
// bool
func Bool(v bool) *bool
func BoolValue(v *bool) bool
func BoolSlice(src []bool) []*bool
func BoolValueSlice(src []*bool) []bool
func BoolMap(src map[string]bool) map[string]*bool
func BoolValueMap(src map[string]*bool) map[string]bool
// int64
func Int64(v int64) *int64
func Int64Value(v *int64) int64
func Int64Slice(src []int64) []*int64
func Int64ValueSlice(src []*int64) []int64
func Int64Map(src map[string]int64) map[string]*int64
func Int64ValueMap(src map[string]*int64) map[string]int64
// int
func Int(v int) *int
func IntValue(v *int) int
func IntSlice(src []int) []*int
func IntValueSlice(src []*int) []int
func IntMap(src map[string]int) map[string]*int
func IntValueMap(src map[string]*int) map[string]int
// float64
func Float64(v float64) *float64
func Float64Value(v *float64) float64
func Float64Slice(src []float64) []*float64
func Float64ValueSlice(src []*float64) []float64
func Float64Map(src map[string]float64) map[string]*float64
func Float64ValueMap(src map[string]*float64) map[string]float64
// time.Time
func Time(v time.Time) *time.Time
func TimeValue(v *time.Time) time.Time
func TimeSlice(src []time.Time) []*time.Time
func TimeValueSlice(src []*time.Time) []time.Time
func TimeMap(src map[string]time.Time) map[string]*time.Time
func TimeValueMap(src map[string]*time.Time) map[string]time.Time
func TimeUnixMilli(t time.Time) int64 // converts time.Time to Unix milliseconds int64
func SecondsTimeValue(v *int64) time.Time // int64 seconds since epoch to time.Time
func MillisecondsTimeValue(v *int64) time.Time // int64 milliseconds since epoch to time.Timefunc IsErrorExpiredCreds(err error) bool
func IsErrorRetryable(err error) bool
func IsErrorThrottle(err error) bool
// Error code constants
const (
ErrCodeSerialization = "SerializationError"
ErrCodeRead = "ReadError"
ErrCodeResponseTimeout = "ResponseTimeout"
ErrCodeRequestCanceled = "RequestCanceled"
InvalidParameterErrCode = "InvalidParameter"
ParamRequiredErrCode = "ParamRequiredError"
ParamMinValueErrCode = "ParamMinValueError"
ParamMinLenErrCode = "ParamMinLenError"
)
var (
ErrMissingRegion = awserr.New("MissingRegion", ...)
ErrMissingEndpoint = awserr.New("MissingEndpoint", ...)
)type Context = context.Context
func BackgroundContext() Context
func SleepWithContext(ctx Context, dur time.Duration) errorfunc AddToUserAgent(r *Request, s string)
func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request)
func MakeAddToUserAgentFreeFormHandler(s string) func(*Request)// Option is a request modification function
type Option func(*Request)
// Built-in request options
func WithAppendUserAgent(s string) Option
func WithGetResponseHeader(key string, val *string) Option
func WithGetResponseHeaders(headers *http.Header) Option
func WithLogLevel(l LogLevel) Option
func WithResponseReadTimeout(duration time.Duration) Option// Create a new request directly (normally done by service clients)
func New(
cfg Config,
metadata Metadata,
handlers Handlers,
retryer Retryer,
operation *Operation,
params interface{},
data interface{},
) *Request// Option is a request modification function
type Option func(*Request)
// Validator interface for parameter validation
type Validator interface {
Validate() error
}
// ReaderSeekerCloser wraps io.Reader with optional Seek/Close
type ReaderSeekerCloser struct { /* ... */ }
func ReadSeekCloser(r io.Reader) ReaderSeekerCloser // Deprecated
func (r ReaderSeekerCloser) Read(p []byte) (int, error)
func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error)
func (r ReaderSeekerCloser) IsSeeker() bool
func (r ReaderSeekerCloser) Close() error
// WriteAtBuffer - in-memory buffer for io.WriterAt (use with s3manager.Downloader)
type WriteAtBuffer struct {
GrowthCoeff float64
// unexported fields
}
func NewWriteAtBuffer(buf []byte) *WriteAtBuffer
func (b *WriteAtBuffer) Bytes() []byte
func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error)
// SDK metadata
const SDKName = "aws-sdk-go"
const SDKVersion = "2.0.0-preview.4"
const WaiterResourceNotReadyErrorCode = "ResourceNotReady"
var NoBody = http.NoBodyInstall with Tessl CLI
npx tessl i tessl/golang-github-com--aws--aws-sdk-go-v2@0.4.0