Reputation: 29316
I'm using literally the example function from the Go docs:
package main
import (
"context"
"fmt"
"github.com/aws/aws-lambda-go/lambda"
)
type MyEvent struct {
Name string `json:"name"`
}
func HandleRequest(ctx context.Context, name MyEvent) (string, error) {
return fmt.Sprintf("Hello %s!", name.Name), nil
}
func main() {
lambda.Start(HandleRequest)
}
If I use the test event console and input { "name": "John" }
it works fine.
But if I go to Add Triggers, click API Gateway, then click Create a new API, set Security to Open, leave everything else default, then click Add then Save.
If I see the URL it lists at the bottom as "API endpoint:" and click it, I get "Internal server error".
If I do curl -XPOST -d "{ \"name\": \"Paul\" }" https://AWS-URL-ENDPOINT/amazonaws.com/default/mytestfunction
I get "Internal server error".
What am I doing wrong?
Upvotes: 3
Views: 1150
Reputation: 216
I had this issue and fixed it by using AWS structure types in my code.
I followed the sample function available here and using events.APIGatewayProxyRequest
and events.APIGatewayProxyResponse
from "github.com/aws/aws-lambda-go/events" as my DTOs.
The APIGatewayProxyRequest
is the parameter your handler needs and events.APIGatewayProxyResponse
is what your handler needs to return.
Upvotes: 2
Reputation: 8464
One of the most common reasons to get Internal server error
is that your Lambda function is either crashing or not returning what is expected by the triggering service.
In this case I suspect a bit of both.
When you proxy through API Gateway your event payload isn't just what you POST'ed. You can find out more about the shape of events here, including those of an API Gateway request: (https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-api-gateway-request).
Your lambda is crashing because the event you get from API Gateway can not be cast into your type MyEvent struct
, as it does not have a name
property; in fact, the body of the request is actually in event.body
as a string which has to be decoded.
A good guide to the events your expected for responses for API Gateway with lambda can be found here (https://serverless.com/framework/docs/providers/aws/events/apigateway/)
Upvotes: 5