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) }
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) }
Deploying Your Lambda
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
The above is the detailed content of Solving the Empty Path Issue in Go Lambda Functions with API Gateway HTTP API. For more information, please follow other related articles on the PHP Chinese website!