BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Invoke Lambda

Go 1.23

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.LoadDefaultConfig to 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 InvocationType to types.InvocationTypeEvent.

Code Breakdown

19
config.LoadDefaultConfig loads the AWS config. It looks for AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION environment variables, making it secure and flexible for different environments.
25
lambda.NewFromConfig(cfg) creates a new Lambda service client. This client holds the connection pool and configuration settings needed to make API requests.
32
client.Invoke sends the request to AWS. We pass the function name and the JSON-encoded payload. The context.TODO() can be replaced with a context containing a timeout.
41
resp.StatusCode indicates the HTTP status of the invocation request itself (e.g., 200 OK), while resp.Payload contains the raw bytes returned by the invoked function.