设置杜松子酒中找不到的路线 [英] Setting up Route Not Found in Gin
本文介绍了设置杜松子酒中找不到的路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在Gin中设置了默认路由器和一些路由:
I've setup a default router and some routes in Gin:
router := gin.Default()
router.POST("/users", save)
router.GET("/users",getAll)
但是我该如何处理杜松子酒中找不到404路线?
but how do I handle 404 Route Not Found in Gin?
最初,我使用的是了解Gin所用的httprouter,所以这就是我本来拥有的...
Originally, I was using httprouter which I understand Gin uses so this was what I originally had...
router.NotFound = http.HandlerFunc(customNotFound)
和功能:
func customNotFound(w http.ResponseWriter, r *http.Request) {
//return JSON
return
}
但这不适用于Gin.
我需要能够使用 c * gin.Context
返回JSON,以便可以使用:
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"})
推荐答案
What you're looking for is the NoRoute
handler.
更准确地说:
r := gin.Default()
r.NoRoute(func(c *gin.Context) {
c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
})
这篇关于设置杜松子酒中找不到的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文