Advanced configuration options provide control over SDK defaults mode, HTTP client behavior, and specialized configuration providers.
This section covers advanced configuration capabilities including SDK defaults modes, HTTP client interfaces, and provider interfaces for specialized configuration scenarios.
type DefaultsModeOptions struct {
Mode aws.DefaultsMode
IMDSClient *imds.Client
}Fields:
Mode - SDK configuration defaults mode. Defaults to legacy if not specified. Supported modes: auto, cross-region, in-region, legacy, mobile, standardIMDSClient - EC2 Instance Metadata Client for environment discovery when aws.DefaultsModeAuto is set. If not specified, SDK constructs a client if IMDS is not disabledThe SDK supports several defaults modes that configure standard behavior patterns:
aws.DefaultsModeAuto - Automatically detects the execution environment and applies appropriate defaultsaws.DefaultsModeLegacy - Maintains backward compatibility with SDK v1 behavioraws.DefaultsModeStandard - Recommended defaults for most use casesaws.DefaultsModeInRegion - Optimized for in-region calls (lower timeouts)aws.DefaultsModeCrossRegion - Optimized for cross-region calls (higher timeouts)aws.DefaultsModeMobile - Optimized for mobile applications (conservative timeouts)func WithDefaultsMode(mode aws.DefaultsMode, optFns ...func(options *DefaultsModeOptions)) LoadOptionsFuncpackage main
import (
"context"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
)
func main() {
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithDefaultsMode(aws.DefaultsModeStandard),
)
if err != nil {
log.Fatal(err)
}
// Use cfg with service clients
}import (
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
)
customIMDSClient := imds.New(imds.Options{
Endpoint: "http://169.254.169.254",
})
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithDefaultsMode(aws.DefaultsModeAuto, func(options *config.DefaultsModeOptions) {
options.IMDSClient = customIMDSClient
}),
)
if err != nil {
log.Fatal(err)
}cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithDefaultsMode(aws.DefaultsModeMobile),
)type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}The HTTPClient interface defines the contract for HTTP client implementations used by the SDK. Any type implementing this interface can be used with WithHTTPClient.
package main
import (
"context"
"crypto/tls"
"log"
"net"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/config"
)
func main() {
// Create custom HTTP client with specific timeouts and TLS config
customHTTPClient := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
},
Timeout: 60 * time.Second,
}
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithHTTPClient(customHTTPClient),
)
if err != nil {
log.Fatal(err)
}
// Use cfg with service clients
}import (
"net/http"
"net/url"
)
// Configure HTTP client with proxy
proxyURL, _ := url.Parse("http://proxy.example.com:8080")
customHTTPClient := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithHTTPClient(customHTTPClient),
)type IgnoreConfiguredEndpointsProvider interface {
GetIgnoreConfiguredEndpoints(ctx context.Context) (bool, bool, error)
}Provider interface for retrieving the flag to disable configured endpoints feature.
func GetIgnoreConfiguredEndpoints(ctx context.Context, configs []interface{}) (value bool, found bool, err error)Used to determine when to disable the configured endpoints feature by searching through configuration sources.
func WithAPIOptions(v []func(*middleware.Stack) error) LoadOptionsFuncAdd custom middleware to the API client request pipeline for cross-cutting concerns like tracing, logging, or request modification.
import (
"github.com/aws/smithy-go/middleware"
)
// Custom middleware to add request ID
func AddRequestID(stack *middleware.Stack) error {
return stack.Initialize.Add(
middleware.InitializeMiddlewareFunc(
"AddRequestID",
func(
ctx context.Context,
in middleware.InitializeInput,
next middleware.InitializeHandler,
) (middleware.InitializeOutput, middleware.Metadata, error) {
// Add custom header or context value
// ...
return next.HandleInitialize(ctx, in)
},
),
middleware.Before,
)
}
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithAPIOptions([]func(*middleware.Stack) error{
AddRequestID,
}),
)func WithAppID(ID string) LoadOptionsFuncSet the SDK app ID that will be included in the user agent header for request attribution and tracking.
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithAppID("my-application-v1.0"),
)func WithAccountIDEndpointMode(m aws.AccountIDEndpointMode) LoadOptionsFuncConfigure how account ID is handled in endpoint resolution. Options include:
aws.AccountIDEndpointModeRequired - Account ID must be availableaws.AccountIDEndpointModePreferred - Account ID used if availableaws.AccountIDEndpointModeDisabled - Account ID not usedcfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithAccountIDEndpointMode(aws.AccountIDEndpointModePreferred),
)func WithDisableRequestCompression(DisableRequestCompression *bool) LoadOptionsFunc
func WithRequestMinCompressSizeBytes(RequestMinCompressSizeBytes *int64) LoadOptionsFuncControl request body compression behavior for supported operations.
// Disable request compression
disableCompression := true
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithDisableRequestCompression(&disableCompression),
)
// Set minimum size for compression (10KB)
minSize := int64(10240)
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithRequestMinCompressSizeBytes(&minSize),
)func WithLogConfigurationWarnings(v bool) LoadOptionsFuncEnable logging of configuration issues and warnings when loading from config sources.
import (
"os"
"github.com/aws/smithy-go/logging"
)
logger := logging.NewStandardLogger(os.Stdout)
cfg, err := config.LoadDefaultConfig(
context.TODO(),
config.WithLogger(logger),
config.WithLogConfigurationWarnings(true),
)type AssumeRoleTokenProviderNotSetError struct{}
func (e AssumeRoleTokenProviderNotSetError) Error() stringError returned when creating a session when the MFAToken option is not set and shared config is configured to assume a role with an MFA token.
type CredentialRequiresARNError struct {
Type string
Profile string
}
func (e CredentialRequiresARNError) Error() stringError for shared config credentials that are incorrectly configured in the shared config or credentials file.
Fields:
Type - Type of credentials that were configuredProfile - Profile name where the credentials were foundcfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
switch e := err.(type) {
case config.CredentialRequiresARNError:
log.Printf("Profile %s requires ARN for %s credentials", e.Profile, e.Type)
case config.AssumeRoleTokenProviderNotSetError:
log.Println("MFA token provider not set for assume role")
default:
log.Fatalf("Failed to load config: %v", err)
}
}aws.DefaultsModeStandard for most applications unless you have specific requirements