Search code examples
amazon-web-servicesgoaws-lambdaserverless

How can I detect a warm-up invocation in a Go AWS Lambda function using the Serverless WarmUp plugin?


I'm using the Serverless WarmUp plugin to keep my Go AWS Lambda function warm. I need to detect when the Lambda function is invoked by the plugin so that I can return a specific response. How can I properly detect a warm-up invocation within my Go code?


Solution

  • You can detect a warm-up invocation in a Go AWS Lambda function by inspecting the client context, which can be done using the lambdacontext package from AWS Lambda's Go SDK. Here's a code snippet that shows how you can do this:

        package main
    
    import (
        "context"
        "github.com/aws/aws-lambda-go/events"
        "github.com/aws/aws-lambda-go/lambda"
        "github.com/aws/aws-lambda-go/lambdacontext"
    )
    
    func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
        lc, _ := lambdacontext.FromContext(ctx)
        if lc.ClientContext.Custom["source"] == "serverless-plugin-warmup" {
            return events.APIGatewayProxyResponse{Body: "Lambda is warm!", StatusCode: 200}, nil
        }
    
        // ... other function logic ...
    
        // Default response for demonstration
        return events.APIGatewayProxyResponse{
            StatusCode: 200,
            Body:       "Hello from Go Lambda!",
        }, nil
    }
    
    func main() {
        lambda.Start(HandleRequest)
    }