Use the AWS SDK for Go v2 by initializing a configured Session or Config object with your region and credentials, then creating specific service clients (like S3 or EC2) from that configuration to perform operations. Unlike v1, v2 uses a modular package structure where you import specific service clients directly and handle errors via the awserr package or standard Go error types.
Here is a practical example of initializing an S3 client and listing buckets:
package main
import (
"context"
"fmt"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
func main() {
// Load default shared configuration (credentials, region, etc.)
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("us-west-2"),
)
if err != nil {
log.Fatalf("unable to load SDK config: %v", err)
}
// Create the S3 client
client := s3.NewFromConfig(cfg)
// List buckets
result, err := client.ListBuckets(context.TODO(), &s3.ListBucketsInput{})
if err != nil {
log.Fatalf("unable to list buckets: %v", err)
}
for _, bucket := range result.Buckets {
fmt.Printf("Bucket: %s\n", *bucket.Name)
}
}
For local development without AWS credentials, you can use the LocalStack endpoint or mock the client. If you need to override the default region or credentials programmatically, pass options to LoadDefaultConfig or use aws.NewConfig().
// Example: Overriding credentials and region explicitly
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("eu-central-1"),
config.WithCredentialsProvider(aws.CredentialsProviderFunc(func(ctx context.Context) (aws.Credentials, error) {
return aws.Credentials{
AccessKeyID: "YOUR_ACCESS_KEY",
SecretAccessKey: "YOUR_SECRET_KEY",
}, nil
})),
)
Key differences from v1 to remember:
- No
awsglobal session: You must explicitly pass theaws.Configto every client constructor. - Context is mandatory: Every API call requires a
context.Contextas the first argument to handle timeouts and cancellation. - Pointers for inputs: Input structs are passed by pointer, and output structs are returned by value.
- Error handling: Errors are standard Go errors; use
awserror type assertions if you need specific error codes, but often checkingerr != nilis sufficient.
Install the SDK using go get github.com/aws/aws-sdk-go-v2/config and the specific service module you need, such as github.com/aws/aws-sdk-go-v2/service/s3.