aws / aws-lambda-go

Libraries, samples and tools to help Go developers develop AWS Lambda functions.
Apache License 2.0
3.58k stars 548 forks source link

Lambda Function Not Routing Correctly with API Gateway #561

Closed Sahil-4555 closed 2 months ago

Sahil-4555 commented 2 months ago
package routes

import (
    "context"
    "fmt"
    "go-sqlc/controllers"

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

func SetupLambda() {
    lambda.Start(HandleLambdaEvent)
}

func HandleLambdaEvent(ctx context.Context, request events.APIGatewayV2HTTPRequest) (*events.APIGatewayV2HTTPResponse, error) {
    var response events.APIGatewayV2HTTPResponse

    fmt.Printf("Request =======>: %v \n", request)
    fmt.Printf("Request Path ======>: %v \n", request.RawPath)
    fmt.Printf("Request Method ======>: %v \n", request.RequestContext.HTTP.Method)

    switch request.RequestContext.HTTP.Method {
    case "GET":
        switch request.RawPath {
        case "/get-customer-orders/{id}":
            return controllers.GetCustomerOrders(ctx, request)
        case "/":
            return controllers.HelloWorld()
        }
    case "POST":
        switch request.RawPath {
        case "/create-customer":
            return controllers.CreateCustomer(ctx, request)
        }
    case "PUT":
        switch request.RawPath {
        case "/update-customer":
            return controllers.UpdateCustomer(ctx, request)
        }
    case "DELETE":
        switch request.RawPath {
        case "/hard-delete-customer/{id}":
            return controllers.HardDeleteCustomer(ctx, request)
        case "/soft-delete-customer/{id}":
            return controllers.SoftDeleteCustomer(ctx, request)
        }
    default:
        response = events.APIGatewayV2HTTPResponse{
            StatusCode: 404,
            Body:       "Not Found",
        }
    }

    return &response, nil
}

Description:

I've created a Lambda function with AWS and configured it to work with an API Gateway. However, I'm encountering an issue where the routing seems to be failing consistently.

Problem:

  1. Route Mismatch: Despite configuring different routes for various HTTP methods, the Lambda function seems to be consistently hitting the default case in the HandleLambdaEvent function, returning a 404 "Not Found" response.

  2. Empty Path and Method: Upon debugging, I found that when the Lambda function is invoked, both the request path and HTTP method appear to be empty strings. This occurs regardless of the actual path or method used in the API request.

Expected Behavior:

Additional Information:

Screenshots

Lamda Function Log From CloudWatch:

Tested Endpoint From API Gateway:

Attached are the CloudWatch logs for the Lambda function during the time of invocation. The logs provide details on the received requests and any errors encountered during processing.