Gin wildcard route conflicts with existing children

蓝咒 提交于 2019-12-11 03:03:07

问题


I'd like to build a gin program which serves the following routes:

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

However, such a program panics at runtime:

[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 '/*'

Is it possible to create a gin program which serves a default resource for every route except for a single one which serves a different resource?

Many pages on the web lead me to believe it is not possible using the default gin router, so what is the easiest way to serve these routes from a gin program?


回答1:


Maybe someone else (like me) will have this error message in a situation where gin.NoRoute() won't be an acceptable fix. I took the following code from github in search for a workaround for this issue:

    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"))
    }
}



回答2:


Looks like the gin.NoRoute(...) function will do the trick.

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

See also https://stackoverflow.com/a/32444263/244128



来源:https://stackoverflow.com/questions/52845807/gin-wildcard-route-conflicts-with-existing-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!