21
votes

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

1 Answers

49
votes

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"})
})