forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slash.go
46 lines (40 loc) · 895 Bytes
/
slash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package middleware
import (
"github.com/labstack/echo"
"net/http"
)
type (
RedirectToSlashOptions struct {
Code int
}
)
// StripTrailingSlash returns a middleware which removes trailing slash from request
// path.
func StripTrailingSlash() echo.HandlerFunc {
return func(c *echo.Context) *echo.HTTPError {
p := c.Request.URL.Path
l := len(p)
if p[l-1] == '/' {
c.Request.URL.Path = p[:l-1]
}
return nil
}
}
// RedirectToSlash returns a middleware which redirects requests without trailing
// slash path to trailing slash path.
func RedirectToSlash(opts ...RedirectToSlashOptions) echo.HandlerFunc {
code := http.StatusMovedPermanently
for _, o := range opts {
if o.Code != 0 {
code = o.Code
}
}
return func(c *echo.Context) (he *echo.HTTPError) {
p := c.Request.URL.Path
l := len(p)
if p[l-1] != '/' {
c.Redirect(code, p+"/")
}
return nil
}
}