Allow empty replacement with ReplacePathRegex middleware

This commit is contained in:
Romain 2024-03-26 13:28:04 +01:00 committed by GitHub
parent 3fcf265d80
commit 7f29595c0a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 23 additions and 1 deletions

View file

@ -53,7 +53,7 @@ func (rp *replacePathRegex) ServeHTTP(rw http.ResponseWriter, req *http.Request)
currentPath = req.URL.EscapedPath() currentPath = req.URL.EscapedPath()
} }
if rp.regexp != nil && len(rp.replacement) > 0 && rp.regexp.MatchString(currentPath) { if rp.regexp != nil && rp.regexp.MatchString(currentPath) {
req.Header.Add(replacepath.ReplacedPathHeader, currentPath) req.Header.Add(replacepath.ReplacedPathHeader, currentPath)
req.URL.RawPath = rp.regexp.ReplaceAllString(currentPath, rp.replacement) req.URL.RawPath = rp.regexp.ReplaceAllString(currentPath, rp.replacement)

View file

@ -44,6 +44,28 @@ func TestReplacePathRegex(t *testing.T) {
expectedRawPath: "/who-am-i/and/who-am-i", expectedRawPath: "/who-am-i/and/who-am-i",
expectedHeader: "/whoami/and/whoami", expectedHeader: "/whoami/and/whoami",
}, },
{
desc: "empty replacement",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: "",
Regex: `/whoami`,
},
expectedPath: "/and",
expectedRawPath: "/and",
expectedHeader: "/whoami/and/whoami",
},
{
desc: "empty trimmed replacement",
path: "/whoami/and/whoami",
config: dynamic.ReplacePathRegex{
Replacement: " ",
Regex: `/whoami`,
},
expectedPath: "/and",
expectedRawPath: "/and",
expectedHeader: "/whoami/and/whoami",
},
{ {
desc: "no match", desc: "no match",
path: "/whoami/and/whoami", path: "/whoami/and/whoami",