如何通过Go语言Lambda Handler获取Serverless Framework的Input参数?
问题描述
我参考多个示例,尝试通过Serverless框架向Go语言AWS Lambda函数传递输入参数,函数配置如下:
functions: schedule: handler: bin/schedule package: artifact: bin/schedule.zip events: - schedule: rate: rate(1 minute) enabled: true input: key: first - schedule: rate: rate(1 minute) input: '{"key": "second"}' enabled: true - schedule: rate: rate(1 minute) input: key: 'third' enabled: true
但标准Lambda Context并未传入我需要的input值。我希望通过该schedule函数运行多个定时任务,用input参数区分不同任务,当前的Handler代码如下:
func Handler(ctx context.Context) error { fmt.Println(fmt.Sprintf("ctx is [%+v]", ctx)) fmt.Println(fmt.Sprintf("ctx value is [%+v]", ctx.Value("schedule"))) lambdaContext, exists := lambdacontext.FromContext(ctx) if exists { fmt.Println(fmt.Sprintf("lambdaContext is [%+v]", lambdaContext)) fmt.Println(fmt.Sprintf("lambdaContext.ClientContext is [%+v]", lambdaContext.ClientContext)) fmt.Println(fmt.Sprintf("lambdaContext.ClientContext.Client is [%+v]", lambdaContext.ClientContext.Client)) fmt.Println(fmt.Sprintf("lambdaContext.ClientContext.Custom is [%+v]", lambdaContext.ClientContext.Custom)) fmt.Println(fmt.Sprintf("lambdaContext.ClientContext.Env is [%+v]", lambdaContext.ClientContext.Env)) } else { fmt.Println("no lambda context") } return nil }
运行输出中未出现first、second或third的值,Custom和Env映射也为空,请问应使用哪种Lambda Handler函数来获取这些input值?
解决方案
你当前的Handler只接收context.Context参数是错误的——Lambda定时事件的input参数并不是通过Context传递的,而是作为Handler的第二个参数传入。
要获取schedule事件的input值,需要修改Handler的签名,添加一个用于接收输入的参数,具体操作如下:
1. 定义输入结构(可选但推荐)
如果你的input结构固定,先定义一个匹配的结构体:
type ScheduleInput struct { Key string `json:"key"` }
如果input结构不固定,也可以直接用map[string]interface{}来接收。
2. 修改Handler签名
将Handler改为接收输入参数的形式,示例如下:
func Handler(ctx context.Context, input ScheduleInput) error { // 直接获取传入的key值 fmt.Println("Received input key:", input.Key) return nil }
如果使用map[string]interface{}接收:
func Handler(ctx context.Context, input map[string]interface{}) error { key := input["key"].(string) fmt.Println("Received input key:", key) return nil }
这样当定时任务触发时,Serverless配置的input内容会被Lambda Go运行时自动反序列化为对应的结构体或map,你就能直接获取到first/second/third这些值了。
补充说明
lambdaContext.ClientContext是用于移动客户端调用Lambda的场景,和定时事件的input无关,所以你之前查看的这个字段始终为空。- Lambda Go运行时会自动处理JSON的反序列化,只要输入结构和你的参数类型匹配即可。
内容的提问来源于stack exchange,提问作者fIwJlxSzApHEZIl
相关产品推荐
相关产品推荐

