Go

How to use the Go AWS SDK with LocalStack.

Overview

The AWS SDK for Go, like other AWS SDKs, lets you set the endpoint when creating resource clients, which is the preferred way of integrating the Go SDK with LocalStack.

The Go SDK has two major versions, each with their own way of specifying the LocalStack endpoint:

Examples

Here is an example of how to create an S3 Client from a Session with the endpoint set to LocalStack. Full examples for both SDK versions can be found in our samples repository.

  1. package main
  2. import (
  3. "github.com/aws/aws-sdk-go/aws"
  4. "github.com/aws/aws-sdk-go/aws/session"
  5. "github.com/aws/aws-sdk-go/service/s3"
  6. "github.com/aws/aws-sdk-go/aws/credentials"
  7. )
  8. func main() {
  9. // Initialize a session
  10. sess, _ := session.NewSession(&aws.Config{
  11. Region: aws.String("us-east-1"),
  12. Credentials: credentials.NewStaticCredentials("test", "test", ""),
  13. S3ForcePathStyle: aws.Bool(true),
  14. Endpoint: aws.String("http://localhost:4566"),
  15. })
  16. // Create S3 service client
  17. client := s3.New(sess)
  18. // ...
  19. }
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "github.com/aws/aws-sdk-go-v2/aws"
  6. "github.com/aws/aws-sdk-go-v2/config"
  7. "github.com/aws/aws-sdk-go-v2/service/s3"
  8. )
  9. func main() {
  10. awsEndpoint = "http://localhost:4566"
  11. awsRegion = "us-east-1"
  12. customResolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) {
  13. if awsEndpoint != "" {
  14. return aws.Endpoint{
  15. PartitionID: "aws",
  16. URL: awsEndpoint,
  17. SigningRegion: awsRegion,
  18. }, nil
  19. }
  20. // returning EndpointNotFoundError will allow the service to fallback to its default resolution
  21. return aws.Endpoint{}, &aws.EndpointNotFoundError{}
  22. })
  23. awsCfg, err := config.LoadDefaultConfig(context.TODO(),
  24. config.WithRegion(awsRegion),
  25. config.WithEndpointResolver(customResolver),
  26. )
  27. if err != nil {
  28. log.Fatalf("Cannot load the AWS configs: %s", err)
  29. }
  30. // Create the resource client
  31. client = s3.NewFromConfig(awsCfg, func(o *s3.Options) {
  32. o.UsePathStyle = true
  33. })
  34. // ...
  35. }

Resources

Last modified October 11, 2021: minor: rename folder Integrations->integrations (68c86019)