From bddad57a7bbd92e6e91db1e05f7376dbec3cb695 Mon Sep 17 00:00:00 2001 From: Kevin Risden Date: Thu, 14 Dec 2017 20:50:07 -0600 Subject: [PATCH] Fix RawPath handling in addPrefix --- middlewares/addPrefix.go | 3 ++ middlewares/addPrefix_test.go | 61 +++++++++++++++++++++++++++-------- 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/middlewares/addPrefix.go b/middlewares/addPrefix.go index 467ca7cf3..306903ae2 100644 --- a/middlewares/addPrefix.go +++ b/middlewares/addPrefix.go @@ -12,6 +12,9 @@ type AddPrefix struct { func (s *AddPrefix) ServeHTTP(w http.ResponseWriter, r *http.Request) { r.URL.Path = s.Prefix + r.URL.Path + if r.URL.RawPath != "" { + r.URL.RawPath = s.Prefix + r.URL.RawPath + } r.RequestURI = r.URL.RequestURI() s.Handler.ServeHTTP(w, r) } diff --git a/middlewares/addPrefix_test.go b/middlewares/addPrefix_test.go index a3af7a7a4..53a1b84c0 100644 --- a/middlewares/addPrefix_test.go +++ b/middlewares/addPrefix_test.go @@ -9,21 +9,56 @@ import ( ) func TestAddPrefix(t *testing.T) { - - path := "/bar" - prefix := "/foo" - - var expectedPath string - handler := &AddPrefix{ - Prefix: prefix, - Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - expectedPath = r.URL.Path - }), + tests := []struct { + desc string + prefix string + path string + expectedPath string + expectedRawPath string + }{ + { + desc: "regular path", + prefix: "/a", + path: "/b", + expectedPath: "/a/b", + }, + { + desc: "raw path is supported", + prefix: "/a", + path: "/b%2Fc", + expectedPath: "/a/b/c", + expectedRawPath: "/a/b%2Fc", + }, } - req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost"+path, nil) + for _, test := range tests { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() - handler.ServeHTTP(nil, req) + var actualPath, actualRawPath, requestURI string + handler := &AddPrefix{ + Prefix: test.prefix, + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + actualPath = r.URL.Path + actualRawPath = r.URL.RawPath + requestURI = r.RequestURI + }), + } - assert.Equal(t, expectedPath, "/foo/bar", "Unexpected path.") + req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost"+test.path, nil) + + handler.ServeHTTP(nil, req) + + assert.Equal(t, test.expectedPath, actualPath, "Unexpected path.") + assert.Equal(t, test.expectedRawPath, actualRawPath, "Unexpected raw path.") + + expectedURI := test.expectedPath + if test.expectedRawPath != "" { + // go HTTP uses the raw path when existent in the RequestURI + expectedURI = test.expectedRawPath + } + assert.Equal(t, expectedURI, requestURI, "Unexpected request URI.") + }) + } }