aws / aws-sdk-go

AWS SDK for the Go programming language.
http://aws.amazon.com/sdk-for-go/
Apache License 2.0
8.64k stars 2.07k forks source link

Lambda function URLs How to Read Body from Post? #4447

Closed jeffotoni closed 7 months ago

jeffotoni commented 2 years ago

Describe the issue

Ex: curl -i -XPOST -H "Content-Type: application/json" https://xxxxxxx.lambda-url.us-east-1.on.aws -d '{"input":"ping"}'

type Event struct {
    Input string `json:"input"`
}

func HandleRequest(event Event) (*Response, error) {
    if len(event.Input) > 0 && event.Input == "ping" {
        return &Response{Msg: "pong"}, nil
    }
    return &Response{Msg: "I don't know"}, nil
}

How to read the body coming from a Post ?

Because the example above didn't work for the curl Payload but for the event it works 100%.

Links

https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html

Jonniedev commented 1 year ago

https://github.com/aws/aws-lambda-go/blob/main/events/README_Lambda.md

RanVaknin commented 1 year ago

Hi @jeffotoni when making a curl request directly you need to unmarshal the body from event before you can access your input.

package main

import (
    "context"
    "encoding/json"
    "fmt"

    "github.com/aws/aws-lambda-go/lambda"
)

type Body struct {
    Input string `json:"input"`
}

type Event struct {
    Body string `json:"body"`
}

type Response struct {
    StatusCode int    `json:"statusCode"`
    Body       string `json:"body"`
}

func HandleRequest(ctx context.Context, event Event) (Response, error) {
    var body Body

    err := json.Unmarshal([]byte(event.Body), &body)
    if err != nil {
        return Response{StatusCode: 400, Body: `{"msg": "error ready body, Invalid JSON"}`}, err
    }

    if body.Input == "ping" {
        return Response{StatusCode: 200, Body: `{"msg": "pong"}`}, nil
    }
    return Response{StatusCode: 200, Body: `{"msg": "I don't know"}`}, nil
}

func main() {
    lambda.Start(HandleRequest)
}
$ curl -i -XPOST -H "Content-Type: application/json" https://xxxxxxx.lambda-url.us-east-1.on.aws/ -d '{"input":"ping"}'

HTTP/1.1 200 OK
Date: Wed, 19 Jul 2023 00:06:57 GMT
Content-Type: application/json
Content-Length: 15
Connection: keep-alive
x-amzn-RequestId: REDACTED
X-Amzn-Trace-Id: REDACTED

{"msg": "pong"}%    

Hope this helps, Thanks, Ran~

jeffotoni commented 1 year ago

I'm going to test it here but it turned out pretty simple lol 😁

github-actions[bot] commented 7 months ago

Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.