diff --git a/error/notfound.go b/error/notfound.go new file mode 100644 index 0000000..a11fb33 --- /dev/null +++ b/error/notfound.go @@ -0,0 +1,18 @@ +package error + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +// NotFound creates a gin middleware for handling page not found. +func NotFound() gin.HandlerFunc { + return func(c *gin.Context) { + c.JSON(http.StatusNotFound, &errorWrapper{ + Error: http.StatusText(http.StatusNotFound), + ErrorCode: http.StatusNotFound, + ErrorDescription: "page not found", + }) + } +} diff --git a/error/notfound_test.go b/error/notfound_test.go new file mode 100644 index 0000000..6046e12 --- /dev/null +++ b/error/notfound_test.go @@ -0,0 +1,18 @@ +package error + +import ( + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestNotFound(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + + NotFound()(ctx) + + assertJSONResponse(t, rec, 404, `{"errorCode":404, "errorDescription":"page not found", "error":"Not Found"}`) +} diff --git a/router/router.go b/router/router.go index 038ede2..c45f7a2 100644 --- a/router/router.go +++ b/router/router.go @@ -21,6 +21,7 @@ func Create(db *database.GormDatabase) (*gin.Engine, func()) { g := gin.New() g.Use(gin.Logger(), gin.Recovery(), error.Handler()) + g.NoRoute(error.NotFound()) g.GET("/")