Use /path/{proxy+} with AWS SAM to have a greedy API in API Gateway
Asked Answered
O

1

6

I'm using SAM. The following setup works:

  Function:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./code/
      Runtime: go1.x
      MemorySize: 64
      Handler: main
      Events:
        TesstApi:
          Type: Api
          Properties:
            Path: /{proxy+}
            Method: any

Now I have a main method (in go)

It looks like this:

package main

import (
    "context"
    "log"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    ginadapter "github.com/awslabs/aws-lambda-go-api-proxy/gin"
    "github.com/gin-gonic/gin"
)

var ginLambda *ginadapter.GinLambda

func Handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    if ginLambda == nil {
        // stdout and stderr are sent to AWS CloudWatch Logs
        log.Printf("Gin cold start")
        r := gin.Default()
        r.GET("/", Index)
        r.GET("/test/hello", xxx)
        r.GET("/test/hi", xxx)

        ginLambda = ginadapter.New(r)
    }

    return ginLambda.ProxyWithContext(ctx, req)
}

func main() {
    lambda.Start(Handler)
}

This works fine. So I can start my local api-gateway with SAM and curl 127.0.0.1:3000/test/hello works well

Now I try to update the following sentence in my template:

  Properties:
    Path: /{proxy+}
    Method: any

to

  Properties:
    Path: /test/{proxy+}
    Method: any

I want to catch everything after the test path.

I tried the following:

    r.GET("/hello", xxx)
    r.GET("hello", xxx)
    r.GET("/test/hello", xxx)

but none of them worked.

Is it possible what I want to do? If yes, How?

Oneeyed answered 13/4, 2020 at 17:20 Comment(0)
A
0

The reason this doesn't work is that gin receives the path from API Gateway RawPath which in your instance would include "/test". So your first router would handle the requests:

 r := gin.Default()
  r.GET("/", Index)
  r.GET("/test/hello", xxx)
  r.GET("/test/hi", xxx)

Curious if you found a solution around this, I am having this issue myself

Anderson answered 13/9, 2022 at 1:45 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewRhona

© 2022 - 2024 — McMap. All rights reserved.