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)
}
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)
}
Deploy your Lambda
- Deploy the Lambda function to AWS.
- Build an HTTP API in API Gateway and integrate it with your Lambda function.
- 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: