How to run AWS lambda go with localstack

Kobe
1 min readDec 14, 2022

--

As you know when we start the application with localstack the endpoint will be run with http://localhost:4566 the easy way to we can attach this endpoint to the AWS config is to determine when we can use S3, DynamoDB Client, and SQS services from localstack

You should define a client and inject the session into services used in the system

We will have a client that includes all AWS Services (S3, DynamoDB, SQS) Client

Create AWS Session connect to localstack (endpoint localhost:4566)

 sess, err := session.NewSessionWithOptions(session.Options{
Profile: profileName,
SharedConfigState: session.SharedConfigEnable,
Config: aws.Config{
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials("test", "test", ""),
S3ForcePathStyle: aws.Bool(true),
Endpoint: aws.String("http://localhost:4566"),
},
})

We will create a client wrapper and include the session for our service

package main

import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/aws/credentials"
...
)

// ClientWrapper hold all our services
type ClientWrapper struct {
DynamoDBClient dynamodbiface.DynamoDBAPI
SQSClient sqsiface.SQSAPI
S3Client s3iface.S3API
}

var (
newDynamoDBClient = dynamodb.New
newSQSClient = sqs.New
newS3Client = s3.New
)

func generateClientWrapper(sess *session.Session) {
var clientWrapper ClientWrapper
clientWrapper.DynamoDBClient = newDynamoDBClient(sess)
clientWrapper.SQSClient = newSQSClient(sess)
clientWrapper.S3Client = newS3Client(sess)
return clientWrapper
}

func iniClient() ClientWrapper {
sess := session.Must(session.NewSession())
return generateClientWrapper(sess)
}

func iniClientWithSession(sess *session.Session) ClientWrapper {
return generateClientWrapper(sess)
}

Now, we can use our client with the local env now

req, _ := clientWrapper.S3Client.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String("mybucket"),
Key: aws.String("key"),
})

--

--

Kobe
Kobe

Written by Kobe

I’m working at KMS-Technology company. I love code (▀̿Ĺ̯▀̿ ̿) — Full Stack Software Engineer

No responses yet