我在 Go 中实现了 Lambda 函数,其中使用 API Gateway POST 方法作为事件触发器,并在我的 serverless.yml 文件中进行配置。但是,我遇到了一个问题,即 API 请求正文中发送的数据始终为空,并且我无法解析它。我应该使用“APIGatewayProxyRequest”以外的其他内容吗?尽管尝试了各种方法,但正文内容从未被填充。任何有关可能导致此情况的原因或如何在这种情况下正确处理请求正文的见解将不胜感激。
这是我的 main.go 中的一个函数:
func handleRequest(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
log.Printf("Request Body: %v", request.Body)
var requestBody RequestBody
if request.Body == "" {
return events.APIGatewayProxyResponse{
StatusCode: 400,
Body: "Request body is empty",
}, nil
}
err := json.Unmarshal([]byte(request.Body), &requestBody)
if err != nil {
log.Printf("Error unmarshalling JSON: %v", err)
return events.APIGatewayProxyResponse{
StatusCode: 400,
Body: "Invalid JSON input",
}, nil
}
response := events.APIGatewayProxyResponse{
StatusCode: 200,
Body: "Success",
}
return response, nil
}
这是来自我的 serverless.yml 的事件:
events:
- http:
path: /test-method
method: post
integration: lambda
private: true
request:
passThrough: NEVER
template:
application/json: ${file(templatefile)}```
我解决了更改模板文件的问题, 在 go APIGatewayProxyRequest 中期待的是这样的:
“正文”:$input.json('$')
但是我的默认模板取自 api-gateway-mapping-template-reference 使用的是这个:
“body-json”:$input.json('$')