2016-03-31 21:17:18 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AddTrailingSlash returns a root level (before router) middleware which adds a
|
|
|
|
// trailing slash to the request `URL#Path`.
|
|
|
|
//
|
|
|
|
// Usage `Echo#Pre(AddTrailingSlash())`
|
|
|
|
func AddTrailingSlash() echo.MiddlewareFunc {
|
2016-04-02 23:19:39 +02:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2016-03-31 21:17:18 +02:00
|
|
|
url := c.Request().URL()
|
|
|
|
path := url.Path()
|
|
|
|
if path != "/" && path[len(path)-1] != '/' {
|
|
|
|
url.SetPath(path + "/")
|
|
|
|
}
|
2016-04-02 23:19:39 +02:00
|
|
|
return next(c)
|
|
|
|
}
|
2016-03-31 21:17:18 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveTrailingSlash returns a root level (before router) middleware which removes
|
|
|
|
// a trailing slash from the request URI.
|
|
|
|
//
|
|
|
|
// Usage `Echo#Pre(RemoveTrailingSlash())`
|
|
|
|
func RemoveTrailingSlash() echo.MiddlewareFunc {
|
2016-04-02 23:19:39 +02:00
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2016-03-31 21:17:18 +02:00
|
|
|
url := c.Request().URL()
|
|
|
|
path := url.Path()
|
|
|
|
l := len(path) - 1
|
|
|
|
if path != "/" && path[l] == '/' {
|
|
|
|
url.SetPath(path[:l])
|
|
|
|
}
|
2016-04-02 23:19:39 +02:00
|
|
|
return next(c)
|
|
|
|
}
|
2016-03-31 21:17:18 +02:00
|
|
|
}
|
|
|
|
}
|