我正在尝试编写简单的 POST 无服务器 Go AWS lambda 函数。
package main
import (
"fmt"
)
import (
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// RequestBodyType is our self-made struct to process JSON request from Client
type RequestBodyType struct {
Event string `string:"event,string,omitempty"`
EventParams EventParamsType
}
// ResponseBodyType is our self-made struct to build response for Client
type ResponseBodyType struct {
Event string `string:"event,string,omitempty"`
EventParams EventParamsType
}
// Probably problematic struct?
type EventParamsType struct {
Name string `json:"name,string,omitempty"`
Age int64 `json:"age,omitempty"`
}
// Handler function Using AWS Lambda Proxy Request
func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
// RequestBody will be used to take the json response from client and build it
requestBody := RequestBodyType{
Event: "",
EventParams: EventParamsType{
Name: "",
Age: 0,
},
}
// Unmarshal the json, return 404 if error
err := json.Unmarshal([]byte(request.Body), &requestBody)
if err != nil {
return events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, nil
}
// We will build the BodyResponse and send it back in json form
responseBody := &ResponseBodyType{
Event: requestBody.Event,
EventParams: EventParamsType{
Name: requestBody.EventParams.Name,
Age: requestBody.EventParams.Age,
},
}
fmt.Println("RESPONSE BODY")
fmt.Println(responseBody)
// Marshal the response into json bytes, if error return 404
response, err := json.Marshal(&responseBody)
if err != nil {
return events.APIGatewayProxyResponse{Body: err.Error(), StatusCode: 404}, nil
}
//Returning response with AWS Lambda Proxy Response
return events.APIGatewayProxyResponse{Body: string(response), StatusCode: 200}, nil
}
func main() {
lambda.Start(Handler)
}
如果我使用单个 JSON 对象键发出 curl 请求,一切正常,例如:
curl -X POST https://my.url/dev/event -d '{"event": "test"}'
我得到回应
{"Event":"test","EventParams":{}
但是,如果我使用嵌套的 json 对象发出请求,例如:
curl -X POST https://my.url/dev/event -d '{"event": "test","eventParams": {"name": "peter","age": 13}}'
然后我得到回应
json: invalid use of ,string struct tag, trying to unmarshal "peter" into string
我相信我可能以错误的方式设计 EventParamsType?还是我以错误的方式构建 ResponseBodyType?