我一直在尝试通过 Amazon API Gateway 在 Go 中运行我的第一个 lambda 函数。
我在 go 中设置了以下包。目标是发送一个 JSON 请求并记录并返回该请求的主体:
package main
import (
"net/http"
"log"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
)
func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
//These log statements return empty regardless of JSON input.
log.Print(request.body)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Body: request.Body
}, nil
}
func main() {
lambda.Start(Handler)
}
我可以构建并压缩它并将其上传到 AWS lambda 管理器。 AWS lambda 管理器包含一个使用测试事件的选项,我可以使用 JSON 字符串对其进行配置
{
"testint": 1,
"teststring": "test"
}
但是,如果我运行这个测试,我会得到以下结果:
{
"statusCode": 200,
"headers": null,
"body": ""
}
我希望正文实际上包含我传递给函数的 json,但显然出了点问题。
最佳答案
我做了一些小改动,然后就可以了
首先,log.Print(request.body)
不能为我编译,但是使用 request.Body
没问题
其次,您用于请求的类型是
// APIGatewayProxyRequest contains data coming from the API Gateway proxy
type APIGatewayProxyRequest struct {
Resource string `json:"resource"` // The resource path defined in API Gateway
Path string `json:"path"` // The url path for the caller
HTTPMethod string `json:"httpMethod"`
Headers map[string]string `json:"headers"`
QueryStringParameters map[string]string `json:"queryStringParameters"`
PathParameters map[string]string `json:"pathParameters"`
StageVariables map[string]string `json:"stageVariables"`
RequestContext APIGatewayProxyRequestContext `json:"requestContext"`
Body string `json:"body"`
IsBase64Encoded bool `json:"isBase64Encoded,omitempty"`
}
在这个 Body 中有一个字段“body”,它是一个字符串。因此,将您的测试数据更改为
{
"body": "HELLO"
}
会给出一些通过的数据
最后,所有例子中Handler的参数好像都有context对象,所以我加了
func Handler(ctx context.Context, request events.APIGatewayProxyRequest)
这是“对我有用”的程序的完整版本
package main
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"log"
"net/http"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
//These log statements return empty regardless of JSON input.
log.Print(request.Body)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Body: request.Body}, nil
}
func main() {
lambda.Start(Handler)
}
关于amazon-web-services - 在 AWS 上测试 Lambda 函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50811927/