Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up Route Not Found in Gin

Tags:

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"}) 
like image 979
tommyd456 Avatar asked Sep 07 '15 17:09

tommyd456


1 Answers

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"}) }) 
like image 175
Pablo Fernandez Avatar answered Oct 05 '22 23:10

Pablo Fernandez