mirror of
https://github.com/labstack/echo.git
synced 2026-05-16 09:48:24 +02:00
+20
-3
@@ -1,6 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "github.com/labstack/echo"
|
||||
import (
|
||||
"github.com/labstack/echo"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type (
|
||||
RedirectToSlashOptions struct {
|
||||
Code int
|
||||
}
|
||||
)
|
||||
|
||||
// StripTrailingSlash removes trailing slash from request path.
|
||||
func StripTrailingSlash() echo.HandlerFunc {
|
||||
@@ -15,8 +24,16 @@ func StripTrailingSlash() echo.HandlerFunc {
|
||||
}
|
||||
|
||||
// RedirectToSlash redirects requests without trailing slash path to trailing slash
|
||||
// path, with status code.
|
||||
func RedirectToSlash(code int) echo.HandlerFunc {
|
||||
// path, with .
|
||||
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)
|
||||
|
||||
@@ -22,10 +22,9 @@ func TestRedirectToSlash(t *testing.T) {
|
||||
req, _ := http.NewRequest(echo.GET, "/users", nil)
|
||||
res := &echo.Response{Writer: httptest.NewRecorder()}
|
||||
c := echo.NewContext(req, res, echo.New())
|
||||
RedirectToSlash(301)(c)
|
||||
println(c.Response.Header().Get("Location"))
|
||||
if res.Status() != 301 {
|
||||
t.Errorf("status code should be 301, found %d", res.Status())
|
||||
RedirectToSlash(RedirectToSlashOptions{Code: http.StatusTemporaryRedirect})(c)
|
||||
if res.Status() != http.StatusTemporaryRedirect {
|
||||
t.Errorf("status code should be 307, found %d", res.Status())
|
||||
}
|
||||
if c.Response.Header().Get("Location") != "/users/" {
|
||||
t.Error("Location header should be /users/")
|
||||
|
||||
Reference in New Issue
Block a user