Gin wildcard route conflicts with existing childre

2019-08-14 22:42发布

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?

2条回答
倾城 Initia
2楼-- · 2019-08-14 22:51

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"))
    }
}
查看更多
一夜七次
3楼-- · 2019-08-14 23:03

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

查看更多
登录 后发表回答