Setting up Route Not Found in Gin

若如初见. 提交于 2019-12-06 18:29:51

问题


I've setup a default router and some routes in Gin:

router := gin.Default()
router.POST("/users", save)
router.GET("/users",getAll)

but how do I handle 404 Route Not Found in Gin?

Originally, I was using httprouter which I understand Gin uses so this was what I originally had...

router.NotFound = http.HandlerFunc(customNotFound)

and the function:

func customNotFound(w http.ResponseWriter, r *http.Request) {
    //return JSON
    return
}

but this won't work with Gin.

I need to be able to return JSON using the c *gin.Context so that I can use:

c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})

回答1:


What you're looking for is the NoRoute handler.

More precisely:

r := gin.Default()

r.NoRoute(func(c *gin.Context) {
    c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
})


来源:https://stackoverflow.com/questions/32443738/setting-up-route-not-found-in-gin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!