设置杜松子酒中找不到的路线

时间:2015-09-07 17:41:08

标签: go go-gin

我在Gin中设置了默认路由器和一些路由:

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

但如何在杜松子酒中找到404 Route Not?

最初,我使用的是我理解Gin使用的httprouter,所以这就是我原来的...

router.NotFound = http.HandlerFunc(customNotFound)

和功能:

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

但这对Gin无效。

我需要能够使用c *gin.Context返回JSON,以便我可以使用:

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

1 个答案:

答案 0 :(得分:29)

您正在寻找的是NoRoute处理程序。

更确切地说:

r := gin.Default()

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