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)
}
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()
}
Most helpful comment
As @ycavatars said, example likes: