You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Go AWS Lambda函数中通过Serverless WarmUp插件检测预热调用?

检测Serverless WarmUp插件发起的Lambda预热调用(Go实现)

核心逻辑

Serverless WarmUp插件发起预热调用时,会在Lambda请求的请求头或自定义事件体中携带专属标识,通过检查这些标识就能区分预热调用与正常业务调用,从而返回特定响应。

具体实现方式

1. 检查默认请求头标识

WarmUp插件默认会在请求头中添加x-warmup: true,你可以在处理APIGateway请求的代码中直接读取该头信息:

package main

import (
	"context"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-lambda-go/events"
)

func handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	// 校验预热请求头
	if warmupFlag, exists := req.Headers["x-warmup"]; exists && warmupFlag == "true" {
		return events.APIGatewayProxyResponse{
			StatusCode: 200,
			Body:       "Warmup completed",
		}, nil
	}

	// 执行正常业务逻辑
	return events.APIGatewayProxyResponse{
		StatusCode: 200,
		Body:       "Business request processed",
	}, nil
}

func main() {
	lambda.Start(handler)
}

2. 检查自定义事件标识

如果你在WarmUp配置中自定义了预热事件(比如设置warmup: { event: { source: "serverless-warmup" } }),可以通过解析事件结构体判断:

package main

import (
	"context"
	"github.com/aws/aws-lambda-go/lambda"
)

// 定义预热事件结构体
type WarmupEvent struct {
	Source string `json:"source"`
}

// 定义正常业务事件结构体
type BusinessEvent struct {
	Payload string `json:"payload"`
}

func handler(ctx context.Context, event interface{}) (string, error) {
	// 尝试断言为预热事件
	if warmupEvt, ok := event.(WarmupEvent); ok && warmupEvt.Source == "serverless-warmup" {
		return "Warmup call handled", nil
	}

	// 处理正常业务请求
	if bizEvt, ok := event.(BusinessEvent); ok {
		return "Processed payload: " + bizEvt.Payload, nil
	}

	return "Unknown event type", nil
}

func main() {
	lambda.Start(handler)
}

注意事项

  • 若你修改了WarmUp的默认标识(比如自定义header键名或事件内容),需要同步调整代码中的校验逻辑。
  • 预热响应尽量精简,避免执行冗余业务逻辑,减少资源消耗。

内容的提问来源于stack exchange,提问作者ASHWIN RAJEEV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:42:05