猿问

将 Golang Gin 与 AWS Lambda 和无服务器与代理路径一起使用

我想通过单个 lambda 函数调用代理来自根目录的所有 HTTP 请求。我尝试/{proxy+}在我的 serverless.yml 中设置为路径。但是当我部署它时,我在访问根目录时收到“此页面未正确重定向”。


serverless.yml 片段


functions:

  hello:

    handler: bin/hello

    url: true

    events:

      - httpApi:

#          path: /{proxy+}

          path: /{any+}

          method: get

主程序



import (

    "fmt"

    "github.com/apex/gateway"

    "github.com/gin-gonic/gin"

    "log"

    "net/http"

    "os"

)


func inLambda() bool {

    if lambdaTaskRoot := os.Getenv("LAMBDA_TASK_ROOT"); lambdaTaskRoot != "" {

        return true

    }

    return false

}


func setupRouter() *gin.Engine {

    gin.SetMode(gin.DebugMode)


    r := gin.Default()


    r.GET("/", func(c *gin.Context) {

        c.JSON(http.StatusOK, gin.H{"message": "home page"})

    })

    r.GET("/hello-world", func(c *gin.Context) {

        c.JSON(http.StatusOK, gin.H{"message": "hello test completed successfully"})

    })


    return r

}


func main() {

    if inLambda() {

        fmt.Println("running aws lambda in aws")

        log.Fatal(gateway.ListenAndServe(":8080", setupRouter()))

    } else {

        fmt.Println("running aws lambda in local")

        log.Fatal(http.ListenAndServe(":8080", setupRouter()))

    }

}


喵喔喔
浏览 138回答 1
1回答

呼唤远方

path: /{proxy+}是正确的。确保您使用的是正确的 apex 版本。apex README声明您需要将 apex v2 用于 HTTP API。您似乎正在使用仅支持 REST API 的 v1。
随时随地看视频慕课网APP

相关分类

Go
我要回答