5

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?

oguz ismail
  • 1
  • 16
  • 47
  • 69
maerics
  • 151,642
  • 46
  • 269
  • 291

3 Answers3

3

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

maerics
  • 151,642
  • 46
  • 269
  • 291
3

Maybe, someone else (like me) will face that error message and will have a situation where gin.NoRoute() is not an acceptable fix.

In search for a workaround to this issue I found the following snippet from 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"))
    }
}
Teocci
  • 7,189
  • 1
  • 50
  • 48
Lucio Mollinedo
  • 2,295
  • 1
  • 33
  • 28
2

You can try like this.

route.GET("/special/*action", func(ctxt *gin.Context) {
  ctxt.JSON(200, gin.H{"message": "WildcardUrl"})
})
  • 4
    Welcome to Stack Overflow! Please read "[Writing The Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)". Formatting is important on SO; Help is available to show how to use it when editing your text. "[How do I format my posts...](https://stackoverflow.com/help/formatting)" will help too. Also, please explain why this should be the selected solution, and how it works; The goal is to educate, not just toss out code. – rizerphe Jun 12 '20 at 14:32