使用Golang Gin+AWS Lambda+Serverless配置代理路径遇根路径重定向异常
问题描述
我希望将所有根路径的HTTP请求通过单个Lambda函数进行代理,尝试在serverless.yml中设置/{proxy+}(后来换成/{any+})作为路径,但部署后访问根路径时出现“This page isn't redirecting properly”错误。
相关代码片段
serverless.yml
functions: hello: handler: bin/hello url: true events: - httpApi: # path: /{proxy+} path: /{any+} method: get
main.go
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())) } }
解决方案
问题核心在于两点:一是HTTP API Gateway的/{proxy+}或/{any+}路径不匹配根路径/;二是Gin框架默认会对带尾部斜杠的请求自动重定向,两者叠加导致循环重定向。
1. 补全Gateway路径配置
修改serverless.yml,同时添加根路径/的匹配规则,确保覆盖所有请求:
functions: hello: handler: bin/hello url: true events: - httpApi: path: / method: get - httpApi: path: /{proxy+} method: get
或者用更简洁的多路径写法:
events: - httpApi: path: - / - /{proxy+} method: get
2. 关闭Gin的自动重定向(可选)
如果想彻底避免尾部斜杠引发的重定向问题,可以在Gin引擎配置中关闭该功能:
func setupRouter() *gin.Engine { gin.SetMode(gin.DebugMode) r := gin.Default() // 关闭尾部斜杠自动重定向 r.RedirectTrailingSlash = false 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 }
3. 验证效果
部署修改后的配置后,访问根路径/会直接匹配Gin的根路由,子路径如/hello-world也能通过/{proxy+}转发到Lambda,重定向错误会消失。
内容的提问来源于stack exchange,提问作者BAR
相关产品推荐
相关产品推荐

