From 3dbd5dcf6e134d8b12875700dfc1c8d3f19dccb2 Mon Sep 17 00:00:00 2001 From: chotow Date: Fri, 24 Jul 2020 22:01:19 +0800 Subject: [PATCH] Fixes the uses of caret(^) at the beginning of the rewrite regex --- middleware/rewrite.go | 3 +++ middleware/rewrite_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/middleware/rewrite.go b/middleware/rewrite.go index d1387af0..476023f6 100644 --- a/middleware/rewrite.go +++ b/middleware/rewrite.go @@ -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 } diff --git a/middleware/rewrite_test.go b/middleware/rewrite_test.go index eb5a46d8..848f0029 100644 --- a/middleware/rewrite_test.go +++ b/middleware/rewrite_test.go @@ -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) +}