首先,有人可能会说这个问题与HTTP request body not getting to AWS lambda function via AWS API Gateway或Getting json body in aws Lambda via API gateway非常相似
但是,这些问题都没有解决使用 Golang 的问题,我一直遇到的问题是找到event
与 Node.js 文档中各处使用的参数等效的参数。
这是我的 Lambda 函数:
package main
import (
"context"
"encoding/json"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/events"
"log"
)
type MyReturn struct {
Response string `json:"response"`
}
type APIGWResponse struct {
IsBase64Encoded bool `json:"isBase64Encoded"`
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
func handle(ctx context.Context, name MyReturn) (APIGWResponse, error) {
log.Print("Called by ", name)
log.Print("context ", ctx)
headers := map[string]string{"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"}
code := 200
response, error := json.Marshal(myReturn{Response:"Hello, " + name.Body})
if error != nil {
log.Println(error)
response = []byte("Internal Server Error")
code = 500
}
return APIGWResponse{true, code, headers, string(response)}, nil
}
func main() {
lambda.Start(handle)
}
问题:MyReturn从 API GW 调用时,对象未填充任何值。该行log.Print("Called by ", name)不会将任何内容附加到字符串Called by。
请求 API GW:
POST -> body: '{"name":"Bob"}', headers: {'Content-Type': 'application/json'}
这是在纯 JS 中执行的,如下所示:
const BASE_URL = "https://my_api_id.execute-api.us-east-1.amazonaws.com/prod/";
const TRIGGER_URL = "my_lambda_function";
function toGW() {
fetch(BASE_URL + TRIGGER_URL, {
method: 'POST',
body: '{"name":"Bimesh"}',
headers:{
'Content-Type': 'application/json'
}
})
.then(data => data.json())
.then(json => console.log(json))
.catch(error => console.log(error));
}
然而,当从 AWS Lambda 控制台对其进行测试时,完全相同的主体仍然有效。
身体:
{"name":"Bob"}
海绵宝宝撒
相关分类