Skip to content

Commit

Permalink
Merge pull request #1588 from choyri/bugfix/rewrite
Browse files Browse the repository at this point in the history
Fixes the uses of caret(^) in rewrite regex
  • Loading branch information
lammel authored Sep 1, 2020
2 parents bcb3165 + 3dbd5dc commit cf2fcad
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
3 changes: 3 additions & 0 deletions middleware/rewrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc {
for k, v := range config.Rules {
k = regexp.QuoteMeta(k)
k = strings.Replace(k, `\*`, "(.*)", -1)
if strings.HasPrefix(k, `\^`) {
k = strings.Replace(k, `\^`, "^", -1)
}
k = k + "$"
config.rulesRegex[regexp.MustCompile(k)] = v
}
Expand Down
27 changes: 27 additions & 0 deletions middleware/rewrite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,30 @@ func TestRewriteWithConfigPreMiddleware_Issue1143(t *testing.T) {
assert.Equal(t, "hosts", string(bodyBytes))
}
}

// Issue #1573
func TestEchoRewriteWithCaret(t *testing.T) {
e := echo.New()

e.Pre(RewriteWithConfig(RewriteConfig{
Rules: map[string]string{
"^/abc/*": "/v1/abc/$1",
},
}))

rec := httptest.NewRecorder()

var req *http.Request

req = httptest.NewRequest(http.MethodGet, "/abc/test", nil)
e.ServeHTTP(rec, req)
assert.Equal(t, "/v1/abc/test", req.URL.Path)

req = httptest.NewRequest(http.MethodGet, "/v1/abc/test", nil)
e.ServeHTTP(rec, req)
assert.Equal(t, "/v1/abc/test", req.URL.Path)

req = httptest.NewRequest(http.MethodGet, "/v2/abc/test", nil)
e.ServeHTTP(rec, req)
assert.Equal(t, "/v2/abc/test", req.URL.Path)
}

0 comments on commit cf2fcad

Please sign in to comment.