Add not found handler

This commit is contained in:
Jannis Mattheis 2018-02-11 22:40:11 +01:00 committed by Jannis Mattheis
parent 74d80765e5
commit c20e999b70
3 changed files with 37 additions and 0 deletions

18
error/notfound.go Normal file
View File

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

18
error/notfound_test.go Normal file
View File

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

View File

@ -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("/")