1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00

Fixed slash middleware

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2016-04-13 13:48:33 -07:00
parent 909f6dacf3
commit 11eafe9b90
2 changed files with 10 additions and 4 deletions

View File

@ -29,9 +29,13 @@ func AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc
rq := c.Request() rq := c.Request()
url := rq.URL() url := rq.URL()
path := url.Path() path := url.Path()
qs := url.QueryString()
if path != "/" && path[len(path)-1] != '/' { if path != "/" && path[len(path)-1] != '/' {
path += "/" path += "/"
uri := path + "?" + url.QueryString() uri := path
if qs != "" {
uri += "?" + qs
}
if config.RedirectCode != 0 { if config.RedirectCode != 0 {
return c.Redirect(config.RedirectCode, uri) return c.Redirect(config.RedirectCode, uri)
} }
@ -59,10 +63,14 @@ func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFu
rq := c.Request() rq := c.Request()
url := rq.URL() url := rq.URL()
path := url.Path() path := url.Path()
qs := url.QueryString()
l := len(path) - 1 l := len(path) - 1
if path != "/" && path[l] == '/' { if path != "/" && path[l] == '/' {
path = path[:l] path = path[:l]
uri := path + "?" + url.QueryString() uri := path
if qs != "" {
uri += "?" + qs
}
if config.RedirectCode != 0 { if config.RedirectCode != 0 {
return c.Redirect(config.RedirectCode, uri) return c.Redirect(config.RedirectCode, uri)
} }

View File

@ -32,7 +32,6 @@ func TestAddTrailingSlash(t *testing.T) {
}) })
h(c) h(c)
assert.Equal(t, http.StatusMovedPermanently, rc.Status()) assert.Equal(t, http.StatusMovedPermanently, rc.Status())
assert.Equal(t, "/add-slash/?key=value", rq.URI())
assert.Equal(t, "/add-slash/?key=value", rc.Header().Get(echo.HeaderLocation)) assert.Equal(t, "/add-slash/?key=value", rc.Header().Get(echo.HeaderLocation))
} }
@ -59,6 +58,5 @@ func TestRemoveTrailingSlash(t *testing.T) {
}) })
h(c) h(c)
assert.Equal(t, http.StatusMovedPermanently, rc.Status()) assert.Equal(t, http.StatusMovedPermanently, rc.Status())
assert.Equal(t, "/remove-slash?key=value", rq.URI())
assert.Equal(t, "/remove-slash?key=value", rc.Header().Get(echo.HeaderLocation)) assert.Equal(t, "/remove-slash?key=value", rc.Header().Get(echo.HeaderLocation))
} }