DEV Community

Cover image for Solving the Empty Path Issue in Go Lambda Functions with API Gateway HTTP API
Rodrigo Burgos
Rodrigo Burgos

Posted on

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

When deploying a Golang/Docker-based HTTP API to AWS Lambda, you may encounter an issue where the path property in the APIGatewayProxyRequest is empty. This occurs because the Lambda function is receiving events from API Gateway HTTP API (v2), which uses a different event structure compared to the REST API (v1).

The Problem

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

The Solution

Switch to using the APIGatewayV2HTTPRequest struct, which includes the RawPath field to handle routing correctly.

The original code from their documentation (which 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 fullscreen mode Exit fullscreen mode

Here’s 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 fullscreen mode Exit fullscreen mode

Deploying Your Lambda

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

Conclusion

Switching to APIGatewayV2HTTPRequest resolves the issue of an empty path in your Lambda function when using API Gateway HTTP API (v2). Make sure to test your endpoint to ensure path routing works as expected.

Sourced from a github issue:

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

Top comments (0)