From 254e691e92ed1d7ba7cbe7187449e94059296fa0 Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Wed, 15 Mar 2023 18:09:16 +0200 Subject: [PATCH] [#2072] registered RemoveTrailingSlash middleware only for the /api/* routes --- apis/base.go | 4 +-- apis/base_test.go | 73 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/apis/base.go b/apis/base.go index 09d6d0b5..8c328d4d 100644 --- a/apis/base.go +++ b/apis/base.go @@ -36,8 +36,8 @@ func InitApi(app core.App) (*echo.Echo, error) { // default middlewares e.Pre(middleware.RemoveTrailingSlashWithConfig(middleware.RemoveTrailingSlashConfig{ Skipper: func(c echo.Context) bool { - // ignore Admin UI route(s) - return strings.HasPrefix(c.Request().URL.Path, trailedAdminPath) + // enable by default only for the API routes + return !strings.HasPrefix(c.Request().URL.Path, "/api/") }, })) e.Use(middleware.Recover()) diff --git a/apis/base_test.go b/apis/base_test.go index 60df5964..947548bf 100644 --- a/apis/base_test.go +++ b/apis/base_test.go @@ -136,3 +136,76 @@ func TestCustomRoutesAndErrorsHandling(t *testing.T) { scenario.Test(t) } } + +func TestRemoveTrailingSlashMiddleware(t *testing.T) { + scenarios := []tests.ApiScenario{ + { + Name: "non /api/* route (exact match)", + Method: http.MethodGet, + Url: "/custom", + BeforeTestFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { + e.AddRoute(echo.Route{ + Method: http.MethodGet, + Path: "/custom", + Handler: func(c echo.Context) error { + return c.String(200, "test123") + }, + }) + }, + ExpectedStatus: 200, + ExpectedContent: []string{"test123"}, + }, + { + Name: "non /api/* route (with trailing slash)", + Method: http.MethodGet, + Url: "/custom/", + BeforeTestFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { + e.AddRoute(echo.Route{ + Method: http.MethodGet, + Path: "/custom", + Handler: func(c echo.Context) error { + return c.String(200, "test123") + }, + }) + }, + ExpectedStatus: 404, + ExpectedContent: []string{`"data":{}`}, + }, + { + Name: "/api/* route (exact match)", + Method: http.MethodGet, + Url: "/api/custom", + BeforeTestFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { + e.AddRoute(echo.Route{ + Method: http.MethodGet, + Path: "/api/custom", + Handler: func(c echo.Context) error { + return c.String(200, "test123") + }, + }) + }, + ExpectedStatus: 200, + ExpectedContent: []string{"test123"}, + }, + { + Name: "/api/* route (with trailing slash)", + Method: http.MethodGet, + Url: "/api/custom/", + BeforeTestFunc: func(t *testing.T, app *tests.TestApp, e *echo.Echo) { + e.AddRoute(echo.Route{ + Method: http.MethodGet, + Path: "/api/custom", + Handler: func(c echo.Context) error { + return c.String(200, "test123") + }, + }) + }, + ExpectedStatus: 200, + ExpectedContent: []string{"test123"}, + }, + } + + for _, scenario := range scenarios { + scenario.Test(t) + } +}