通过API GW调用时AWS Lambda Go函数未获取请求主体 [英] AWS Lambda Go function not getting request body when called via API GW

查看:106
本文介绍了通过API GW调用时AWS Lambda Go函数未获取请求主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,有人可能会说这个问题与通过API网关在AWS Lambda中获取json正文

First off, one might say this question is very similar to HTTP request body not getting to AWS lambda function via AWS API Gateway or Getting json body in aws Lambda via API gateway

但是,这些问题都没有解决使用Golang的问题,而我一直遇到的问题是找到与Node.js文档中各处使用的event参数等效的问题.

However, none of these questions address using Golang, and the problem I have been having is finding an equivalent of the event parameter used everywhere in the Node.js documentation.

这是我的Lambda函数:

Here's my Lambda Function:

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)
}

问题:从API GW调用时,MyReturn对象未填充任何值. log.Print("Called by ", name)行不会将任何内容附加到Called by字符串.

Problem: the MyReturn object is not being filled with any value when called from API GW. The line log.Print("Called by ", name) results in nothing being appended to the Called by string.

对API GW的请求:

Request to API GW:

 POST -> body: '{"name":"Bob"}', headers: {'Content-Type': 'application/json'}

这是在纯JS中执行的,如下所示:

This is being performed in pure JS as follows:

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控制台进行测试时,完全相同的主体可以工作.

And yet, the exact same body works when testing it from the AWS Lambda console.

身体:

{"name":"Bob"}

推荐答案

结果是,即使我无法在面向用户的网站上找到任何文档,也确实存在.阅读此内容: https://github.com/aws/aws-lambda-go/blob/master/events/README_ApiGatewayEvent.md

Turns out, even though I wasn't able to find any documentation on this on a user-facing website, documentation does exist. Read this: https://github.com/aws/aws-lambda-go/blob/master/events/README_ApiGatewayEvent.md

到目前为止,这是我想出的最简单的方法来从API GW接收数据并响应来自其的请求:

Here's the simplest way I've figured out so far to receive data from and respond to a request from API GW:

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"`
}

func handle(ctx context.Context, name events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    log.Print("Request body: ", 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 events.APIGatewayProxyResponse {code, headers, string(response), false}, nil
}

func main() {
    lambda.Start(handle)
}

在这种情况下,log.Print("Request body: ", name)行会导致记录准确的请求正文.问题解决了.

In this case, the log.Print("Request body: ", name) line results in the exact request body being logged. Problem solved.

注意:同样,我也不必从问题中创建该APIGWResponse对象,该events.APIGatewayProxyResponse是完全相同的东西,已经为您量身定做了.这些对象都在此类内: https://github .com/aws/aws-lambda-go/blob/master/events/apigw.go

Note: Also I didn't have to create that APIGWResponse object from the question, the events.APIGatewayProxyResponse is the exact same thing, already made for you. These objects are all inside this class: https://github.com/aws/aws-lambda-go/blob/master/events/apigw.go

这篇关于通过API GW调用时AWS Lambda Go函数未获取请求主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆