如何使用无服务器WarmUp插件检测Go AWS Lambda函数中的预热调用?

atmip9wb  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(82)

我正在使用Serverless WarmUp插件来保持我的Go AWS Lambda函数温暖。我需要检测插件何时调用Lambda函数,以便返回特定的响应。如何正确检测Go代码中的预热调用?

ohtdti5x

ohtdti5x1#

您可以通过检查客户端上下文来检测Go AWS Lambda函数中的预热调用,这可以使用AWS Lambda的Go SDK中的lambdacontext包来完成。下面的代码片段展示了如何做到这一点:

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)
}

相关问题