2015-05-14 08:07:03 +02:00
|
|
|
package middleware
|
|
|
|
|
2015-05-15 01:25:49 +02:00
|
|
|
import (
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
RedirectToSlashOptions struct {
|
|
|
|
Code int
|
|
|
|
}
|
|
|
|
)
|
2015-05-14 08:07:03 +02:00
|
|
|
|
2015-05-18 07:54:29 +02:00
|
|
|
// StripTrailingSlash returns a middleware which removes trailing slash from request
|
|
|
|
// path.
|
2015-05-14 08:07:03 +02:00
|
|
|
func StripTrailingSlash() echo.HandlerFunc {
|
2015-05-20 23:38:51 +02:00
|
|
|
return func(c *echo.Context) error {
|
2015-05-14 08:07:03 +02:00
|
|
|
p := c.Request.URL.Path
|
|
|
|
l := len(p)
|
|
|
|
if p[l-1] == '/' {
|
|
|
|
c.Request.URL.Path = p[:l-1]
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-18 07:54:29 +02:00
|
|
|
// RedirectToSlash returns a middleware which redirects requests without trailing
|
|
|
|
// slash path to trailing slash path.
|
2015-05-15 01:25:49 +02:00
|
|
|
func RedirectToSlash(opts ...RedirectToSlashOptions) echo.HandlerFunc {
|
|
|
|
code := http.StatusMovedPermanently
|
|
|
|
|
|
|
|
for _, o := range opts {
|
|
|
|
if o.Code != 0 {
|
|
|
|
code = o.Code
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-20 23:38:51 +02:00
|
|
|
return func(c *echo.Context) error {
|
2015-05-14 08:07:03 +02:00
|
|
|
p := c.Request.URL.Path
|
|
|
|
l := len(p)
|
|
|
|
if p[l-1] != '/' {
|
|
|
|
c.Redirect(code, p+"/")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|