Gin wildcard route conflicts with existing children

maerics picture maerics · Oct 17, 2018 · Viewed 7.5k times · Source

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?

Answer

Lucio Mollinedo picture Lucio Mollinedo · Nov 2, 2018

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