Gin: Is there a way to define NoRoute for group of routes?

Created on 1 Nov 2017  路  2Comments  路  Source: gin-gonic/gin

I have some group of routes. I want to handle different NoRoute for each of groups.
Is there a way to do that?

example:

show := router.Group("/show")
{
    show.GET("/show/:filename", ShowFile)
    show.NoRoute(ShowNoRoute)
}

Most helpful comment

As @ycavatars said, example likes:

func main() {
    router := gin.Default()
    router.NoRoute(func(c *gin.Context) {
        path := c.Request.URL.Path
        method := c.Request.Method
        fmt.Println(path)
        fmt.Println(method)
        if strings.HasPrefix(path, "/show") {
            fmt.Println("ok")
        }
    })
    router.Run()
}

All 2 comments

I think you can't do that because NoRoute method is defined on Engine struct but the Group method returns a *RouterGroup. Maybe you can dispatch the NoRoute events to different handlers by parsing the request URL path. Here's an example:

router.NoRoute(func(c *gin.Context) {
  path := c.Request.URL.Path
  // if path is under `/show` group, call the show group NoRoute
  // else call the default NoRoute
})

As @ycavatars said, example likes:

func main() {
    router := gin.Default()
    router.NoRoute(func(c *gin.Context) {
        path := c.Request.URL.Path
        method := c.Request.Method
        fmt.Println(path)
        fmt.Println(method)
        if strings.HasPrefix(path, "/show") {
            fmt.Println("ok")
        }
    })
    router.Run()
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gplume picture gplume  路  3Comments

boneq picture boneq  路  3Comments

kekemuyu picture kekemuyu  路  3Comments

xpbliss picture xpbliss  路  3Comments

Bloomca picture Bloomca  路  3Comments