Naguib Ihab
Naguib Ihab

Reputation: 4496

Passing JSON when invoking function using serverless

I am running a lambda function written in Go using Serverless and I want to pass a couple of parameters to it when it's invoked.

Here's the struct I created to receive the request:

type RequestStruct struct {
    StartAt int `json:"startAt"`
    EndAt   int `json:"endAt"`
}

And in the handler I'm trying to print out the values:

func Handler(ctx context.Context,request RequestStruct) (Response, error) {
    fmt.Printf("Request: %v",request)

I tried invoking it using the --raw option, so I tried doing this

serverless invoke -f orders --raw -d '{"startAt":1533513600,"endAt":1534118399}'

and I tried wrapping it in double quotes instead

serverless invoke -f orders --raw -d "{startAt:1533513600,endAt:1534118399}"

serverless invoke -f orders --raw -d "{\"startAt\":1533513600,\"endAt\":1534118399}"

I received a marshal error with all three:

{
    "errorMessage": "json: cannot unmarshal string into Go value of type main.RequestStruct",
    "errorType": "UnmarshalTypeError"
}

I'm not sure what I am doing wrong and I can find any examples for that online, there's only this serverless doc about how to do the invoke and this aws doc about how to handle the event in Go

Update I tried invoking the event from the AWS Console and it worked, so odds are the issue is in the serverless invoke command.

Upvotes: 2

Views: 2982

Answers (2)

Adam Knights
Adam Knights

Reputation: 2151

Incase you hit this issue when running the command via npm. I also had a similar error when invoking it with:

    "invoke": "serverless invoke --function myfunction --data \"{ \"Records\": []}\"",

By changing the double quotes to single quotes on the data it then suddenly started working:

    "invoke": "serverless invoke --function myfunction --data '{ \"Records\": []}'",

Upvotes: 0

Naguib Ihab
Naguib Ihab

Reputation: 4496

I found a way around this by having my JSON in a file rather than in the command itself, this doesn't solve the issue I'm experiencing in the question but it's a way to invoke the function with Json

I added a events/startAndEnd.json file that contains my json data:

{
    "startAt":1533513600,
    "endAt":1534118399
}

And referenced that file in the invoke command: serverless invoke -f orders --path events/startAndEnd.json

Upvotes: 1

Related Questions