AWS Lambda Go function not getting request body when called via API GW

血红的双手。 提交于 2019-12-05 17:45:52

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

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

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

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

Well I don't have enough reputation to respond to @laurids' comment... so I guess StackOverflow forces me to make a new answer (?). lol

laurids I was surprised to find that, when I send the following lambda Test Event, I get an empty request body in golang

{
  "name": "Bob"
}

I have to do this to set the request body. hope it helps!

{
  "body": "{\"name\": \"Bob\"}"
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!