From 4df75cd2b2bae67f34a26ba8f17528805c463562 Mon Sep 17 00:00:00 2001 From: Taichi Sasaki Date: Thu, 28 Sep 2023 09:34:14 +0900 Subject: [PATCH] Use RedirectSlashes middleware by default Goa mux (#3366) * Test redirection for URLs with trailing slashes * Use RedirectSlashes middleware by default Goa mux * Mount at the top level of the router --- http/mux.go | 4 ++++ http/mux_test.go | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/http/mux.go b/http/mux.go index f918c877fd..11013ecb3a 100644 --- a/http/mux.go +++ b/http/mux.go @@ -8,6 +8,7 @@ import ( "regexp" chi "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" ) type ( @@ -79,6 +80,9 @@ type ( // NewMuxer returns a Muxer implementation based on a Chi router. func NewMuxer() ResolverMuxer { r := chi.NewRouter() + // RedirectSlashes must be mounted at the top level of the router. + // See. https://github.com/go-chi/chi/blob/1129e362d6cce6e3805e3bc8dfbaeb34b5129789/middleware/strip_test.go#L105-L107 + r.Use(middleware.RedirectSlashes) r.NotFound(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { ctx := context.WithValue(req.Context(), AcceptTypeKey, req.Header.Get("Accept")) enc := ResponseEncoder(ctx, w) diff --git a/http/mux_test.go b/http/mux_test.go index f3eacc1798..94f59781db 100644 --- a/http/mux_test.go +++ b/http/mux_test.go @@ -227,6 +227,16 @@ func TestResolvePattern(t *testing.T) { w := httptest.NewRecorder() mux.ServeHTTP(w, req) assert.True(t, called) + // Make sure the URL with a trailing slash is redirected. + called = false // Reset. + req, _ = http.NewRequest("GET", c.URL+"/", nil) + w = httptest.NewRecorder() + mux.ServeHTTP(w, req) + assert.Equal(t, http.StatusMovedPermanently, w.Code) + req, _ = http.NewRequest("GET", w.Header().Get("Location"), nil) + w = httptest.NewRecorder() + mux.ServeHTTP(w, req) + assert.True(t, called) }) } }