杜松子酒通配符路由与现有子项冲突



>我想建立一个gin程序,它服务于以下路线:

r.GET("/special", ... // Serves a special resource.
r.Any("/*", ...       // Serves a default resource.

但是,这样的程序在运行时会崩溃:

[GIN-debug] GET    /special                  --> main.main.func1 (2 handlers)
[GIN-debug] GET    /*                        --> main.main.func2 (2 handlers)
panic: wildcard route '*' conflicts with existing children in path '/*'

是否可以创建一个 gin 程序,为每条路由提供默认资源,除了提供不同资源的单个路由?

网络上的许多页面让我相信使用默认的 gin 路由器是不可能的,那么从 gin 程序提供这些路由的最简单方法是什么?

看起来gin.NoRoute(...)函数可以解决问题。

r.GET("/special", func(c *gin.Context) { // Serve the special resource...
r.NoRoute(func(c *gin.Context) {         // Serve the default resource...

另请参阅 https://stackoverflow.com/a/32444263/244128

也许,其他人(像我一样(会遇到该错误消息,并且会遇到gin.NoRoute()不可接受的修复程序的情况。

在寻找解决此问题的方法时,我从 github 中找到了以下代码片段:

...
router.GET("/v1/images/:path1", GetHandler)           // /v1/images/detail
router.GET("/v1/images/:path1/:path2", GetHandler)    // /v1/images/<id>/history
...
func GetHandler(c *gin.Context) {
path1 := c.Param("path1")
path2 := c.Param("path2")
if path1 == "detail" && path2 == "" {
Detail(c)
} else if path1 != "" && path2 == "history" {
imageId := path1
History(c, imageId)
} else {
HandleHttpError(c, NewHttpError(404, "Page not found"))
}
}

你可以这样尝试。

route.GET("/special/*action", func(ctxt *gin.Context) {
ctxt.JSON(200, gin.H{"message": "WildcardUrl"})
})

最新更新