1
0
mirror of https://github.com/labstack/echo.git synced 2026-05-16 09:48:24 +02:00

Middleware with options

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2015-05-14 16:25:49 -07:00
parent 58ed17d35e
commit f5a385b547
3 changed files with 27 additions and 11 deletions
+20 -3
View File
@@ -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)
+3 -4
View File
@@ -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/")