Go by Example: Invoke Lambda
Programmatically invoke other Lambda functions using the AWS SDK for Go v2. This sample shows how to configure the client, create a payload, and execute a synchronous invocation.
Code
package main
import (
"context"
"encoding/json"
"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/lambda"
)
type Payload struct {
Name string `json:"name"`
}
func main() {
// Load AWS configuration (credentials from env vars or ~/.aws/config)
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-east-1"))
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
// Create a Lambda client
client := lambda.NewFromConfig(cfg)
// Prepare the payload
payload := Payload{Name: "Alice"}
payloadBytes, _ := json.Marshal(payload)
// Invoke the function
resp, err := client.Invoke(context.TODO(), &lambda.InvokeInput{
FunctionName: aws.String("my-target-function"),
Payload: payloadBytes,
})
if err != nil {
log.Fatalf("Error invoking function: %v", err)
}
// Print the response status and payload
fmt.Printf("Status: %d\n", resp.StatusCode)
fmt.Printf("Response: %s\n", string(resp.Payload))
}Explanation
Invoking one Lambda function from another, or from any Go application, is achieved using the AWS SDK for Go v2. This capability is essential for building microservices architectures where functions need to communicate or orchestrate workflows. The SDK provides a robust and type-safe way to interact with AWS services.
The process begins with loading the AWS configuration, which automatically resolves credentials and region settings from the environment. A service-specific client is then created using this configuration. This client manages the underlying HTTP connections and authentication, allowing you to focus on the application logic.
When invoking a function, you can choose between synchronous (RequestResponse) and asynchronous (Event) invocation types. Synchronous invocation waits for the function to complete and returns the result, while asynchronous invocation queues the event and returns immediately. The SDK handles the serialization of the payload and the parsing of the response.
- Configuration: Use
config.LoadDefaultConfigto automatically load credentials and region settings from environment variables or shared config files. This follows security best practices by avoiding hardcoded secrets. - Client Initialization: Create a service-specific client (e.g.,
lambda.NewFromConfig) using the loaded configuration. This client is thread-safe and should be reused. - Invocation Types: You can invoke functions synchronously (RequestResponse, default) or asynchronously (Event). For async invocations, set
InvocationTypetotypes.InvocationTypeEvent.

