doudao1369 2018-11-01 03:14
浏览 75
已采纳

使用Go设置AWS Lambda,为什么我总是通过此简单功能收到“内部服务器错误”?

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?

  • 写回答

1条回答 默认 最新

  • duan6301 2018-11-01 10:16
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?