Search code examples
goaws-lambdaaws-api-gatewayaws-http-api

Amazon API Gateway HTTP API: Custom types in lambda functions in go


I am a little bit confused about how to get custom types passed into my Lambda function using golang and sitting behind a HttpApi.

Consider the following go lambda handler, which is almost a copy of the example from the documentation.


type MyRequestType struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type MyResponseType struct {
    Message string `json:"message"`
}

func handler(request MyRequestType) (MyResponseType, error) {
    log.Printf("received request: %v", request)
    return MyResponseType{Message: fmt.Sprintf("Hello %s, you are %d years old!", request.Name, request.Age)}, nil
}

func main() {
    lambda.Start(handler)
}

The resulting message is always the following.

{
    "message": "Hello , you are 0 years old!"
}

I have the dump feeling that this is not possible in Amazon API Gateway HTTP API. But I also haven't found any documentation pointing out, that this is not possible. So I really wonder, if I am doing something wrong?

The documentation says also something about the valid signatures:

For example func (context.Context, TIn) (TOut, error)

If I am using a HTTP API with the Payload format version 2:

Is the context.Context the normal golang context or something special? I am thinking of events.APIGatewayV2HTTPRequestContext or others.

What would be the right type of TIn and TOut => events.APIGatewayV2HTTPRequest and events.APIGatewayV2HTTPResponse?


Solution

  • Is the context.Context the normal golang context

    Yes.

    But you can get the Lambda context with lambdacontext.FromContext which contains additional lambda-specific metadata.

    What would be the right type of TIn and TOut

    It depends on who invokes the Lambda. When the Lambda is invoked by another AWS service, including the API Gateway, the so-called TIn and TOut are types from the lambda event package. Quote from the package introduction:

    This package provides input types for Lambda functions that process AWS events.

    In case of the API Gateway, that would be events.APIGatewayProxyRequest and Response, or presumably for the Payload format version 2 the events.APIGatewayV2HTTPRequest and Response — which were added in v1.16.0.

    Further documentation (but not much) in the github repo README