Solving the Empty Path Issue in Go Lambda Functions with API Gateway HTTP API – DEV Community
December 23, 2024

Solving the Empty Path Issue in Go Lambda Functions with API Gateway HTTP API – DEV Community

When deploying Golang/Docker-based HTTP API to AWS Lambda, you may encounter the problem that the path attribute in APIGatewayProxyRequest is empty. This happens because the Lambda function is receiving events from the API Gateway HTTP API (v2), which uses a different event structure than the REST API (v1).

question

APIGatewayProxyRequest is designed for older REST APIs and will result in empty path fields when used with HTTP APIs. The solution is to use the correct event structure: APIGatewayV2HTTPRequest.

solution

Switched to using the APIGatewayV2HTTPRequest structure, which includes a RawPath field to correctly handle routing.

Original code from their documentation (doesn’t work):

package main

import (
    "context"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    response := events.APIGatewayProxyResponse{
        StatusCode: 200,
        Body:       "\"Hello from Lambda!\"",
    }
    return response, nil
}

func main() {
    lambda.Start(handler)
}
Enter full screen mode

Exit full screen mode

Here is an updated Lambda function example:

package main

import (
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handler(request events.APIGatewayV2HTTPRequest) (*events.APIGatewayV2HTTPResponse, error) {
    if request.RawPath == "/health" {
        return &events.APIGatewayV2HTTPResponse{
            StatusCode: 200,
            Body:       "Health check passed",
        }, nil
    }
    return &events.APIGatewayV2HTTPResponse{
        StatusCode: 404,
        Body:       "Not Found",
    }, nil
}

func main() {
    lambda.Start(handler)
}
Enter full screen mode

Exit full screen mode

Deploy your Lambda

  1. Deploy the Lambda function to AWS.
  2. Build an HTTP API in API Gateway and integrate it with your Lambda function.
  3. Test endpoint: Requests to /health should return a success message, while any other path will return a 404.

in conclusion

Switching to APIGatewayV2HTTPRequest resolves issues with empty paths in Lambda functions when using the API Gateway HTTP API (v2). Be sure to test your endpoints to ensure path routing works as expected.

From github issue:

https://github.com/aws/aws-lambda-go/issues/60

2024-12-23 00:11:13

Leave a Reply

Your email address will not be published. Required fields are marked *