Rest Gin错误:通配符路由与现有子级冲突
我正在使用并尝试实现嵌套路由,如下所示:Rest Gin错误:通配符路由与现有子级冲突,rest,go,routing,web-frameworks,Rest,Go,Routing,Web Frameworks,我正在使用并尝试实现嵌套路由,如下所示: // SetupRouter initialize routes and handlers func SetupRouter() *gin.Engine { r := gin.Default() r.GET("/", controllers.Welcome) r.GET("/resources", controllers.GetResources) r.GET("/resources/otherroute", c
// SetupRouter initialize routes and handlers
func SetupRouter() *gin.Engine {
r := gin.Default()
r.GET("/", controllers.Welcome)
r.GET("/resources", controllers.GetResources)
r.GET("/resources/otherroute", controllers.GetOResources)
r.GET("/resources/:id", controllers.GetResourcesByID)
r.GET("/resources/:id/sub-resources", GetSubResources)
r.GET("/resources/:id/sub-resources/:srid", GetSubResourcesByID)
r.GET("/resources/:id/sub-resources/:srid/ssub-resources", GetSSubResources)
r.GET("/resources/:id/sub-resources/:srid/ssub-resources/:ssrid", GetSSubResourcesByID)
// .... etc.
return r
}
但我有一些奇怪的错误:
[GIN-debug] GET / --> github.com/badis/so-
gin-nested-routes/controllers.Welcome (3 handlers)
[GIN-debug] GET /resources --> github.com/badis/so-gin-nested-routes/controllers.GetResources (3 handlers)
[GIN-debug] GET /resources/otherroute --> github.com/badis/so-gin-nested-routes/controllers.GetOResources (3 handlers)
[GIN-debug] GET /resources/:id --> github.com/badis/so-gin-nested-routes/controllers.GetResourcesByID (3 handlers)
panic: wildcard route ':id' conflicts with existing children in path '/resources/:id'
goroutine 1 [running]:
github.com/gin-gonic/gin.(*node).insertChild(0xc0002516c0, 0xc0001edc01, 0xc0002325eb, 0x3, 0xc0002325e0, 0xe, 0xc000224300, 0x3, 0x3)
/home/badis/go/src/github.com/gin-gonic/gin/tree.go:294 +0x807
github.com/gin-gonic/gin.(*node).addRoute(0xc0002516c0, 0xc0002325e0, 0xe, 0xc000224300, 0x3, 0x3)
/home/badis/go/src/github.com/gin-gonic/gin/tree.go:255 +0x4ea
我无法在国内外找到令人满意的解决方案
如果您想快速重现这个问题,请看这里:Gin无法将
/resources/otherroute
与/resources/:id
区分开来,因为otherroute
可以解释为:id
,因此您会遇到冲突。我相信您不能将动态段与静态段混为一谈。您可以使用/resources/otherroute
或/resources/:id
,但不能同时使用两者。它在express.js中工作得很好,但我可以看到Gin还没有。它可以检查/resources/otherroute
。如果不匹配,请在:id
中找到任何内容。只要它没有更多的部分,比如:/resources/:id/sub-resources
是的,对路由进行优先级排序是有意义的。但可能有一个原因,为什么它没有这样做。不管是哪种方式,都可以接受答案或接近问题:-)