Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
mweglarz authored and vishr committed Aug 15, 2018
1 parent 2017e5e commit 74f9806
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
3 changes: 2 additions & 1 deletion middleware/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc {
// Initialize
for k, v := range config.Rules {
k = strings.Replace(k, "*", "(.*)", -1)
k = k + "$"
config.rulesRegex[regexp.MustCompile(k)] = v
}

Expand All @@ -74,9 +75,9 @@ func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc {
replacer := captureTokens(k, req.URL.Path)
if replacer != nil {
req.URL.Path = replacer.Replace(v)
break
}
}

return next(c)
}
}
Expand Down
33 changes: 33 additions & 0 deletions middleware/rewrite_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package middleware

import (
"io/ioutil"
"net/http/httptest"
"testing"

Expand Down Expand Up @@ -61,3 +62,35 @@ func TestEchoRewritePreMiddleware(t *testing.T) {
assert.Equal(t, "/new", req.URL.Path)
assert.Equal(t, 200, rec.Code)
}

// Issue #1143
func TestRewriteWithConfigPreMiddleware_Issue1143(t *testing.T) {
e := echo.New()
r := e.Router()

e.Pre(RewriteWithConfig(RewriteConfig{
Rules: map[string]string{
"/api/*/mgmt/proj/*/agt": "/api/$1/hosts/$2",
"/api/*/mgmt/proj": "/api/$1/eng",
},
}))

r.Add(echo.GET, "/api/:version/hosts/:name", func(c echo.Context) error {
return c.String(200, "hosts")
})
r.Add(echo.GET, "/api/:version/eng", func(c echo.Context) error {
return c.String(200, "eng")
})

for i := 0; i < 100; i++ {
req := httptest.NewRequest(echo.GET, "/api/v1/mgmt/proj/test/agt", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, "/api/v1/hosts/test", req.URL.Path)
assert.Equal(t, 200, rec.Code)

defer rec.Result().Body.Close()
bodyBytes, _ := ioutil.ReadAll(rec.Result().Body)
assert.Equal(t, "hosts", string(bodyBytes))
}
}

0 comments on commit 74f9806

Please sign in to comment.