From f1532f9ea0bee961394ab0d609f0e87860d42f04 Mon Sep 17 00:00:00 2001 From: Richard Carson Derr Date: Wed, 2 Oct 2024 22:48:08 -0400 Subject: [PATCH] feat(issue-295): register trailing slash and non-trailing slash endpoints to avoid redirects --- rest/mux/mux.go | 30 ++++++++++++++++++++++++++++++ rest/mux/mux_test.go | 6 ++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/rest/mux/mux.go b/rest/mux/mux.go index 37ebe98..cba5039 100644 --- a/rest/mux/mux.go +++ b/rest/mux/mux.go @@ -9,7 +9,9 @@ package mux import ( "fmt" "net/http" + "path" "slices" + "strings" "sync" ) @@ -72,6 +74,34 @@ func NewHttp(opts ...HttpOption) *Http { func (m *Http) Handle(method Method, pattern string, h http.Handler) { m.pathMethods[pattern] = append(m.pathMethods[pattern], method) m.mux.Handle(fmt.Sprintf("%s %s", method, pattern), h) + + // {$} is a special case where we only want to exact match the path pattern. + if strings.HasSuffix(pattern, "{$}") { + return + } + + if strings.HasSuffix(pattern, "/") { + withoutTrailingSlash := pattern[:len(pattern)-1] + if len(withoutTrailingSlash) == 0 { + return + } + + m.pathMethods[withoutTrailingSlash] = append(m.pathMethods[withoutTrailingSlash], method) + m.mux.Handle(fmt.Sprintf("%s %s", method, withoutTrailingSlash), h) + return + } + + // if the end of the path contains the "..." wildcard segment + // then we can't add a "/" to it since "..." should not be followed + // by a "/", per the http.ServeMux docs. + base := path.Base(pattern) + if strings.Contains(base, "...") { + return + } + + withTrailingSlash := pattern + "/" + m.pathMethods[withTrailingSlash] = append(m.pathMethods[withTrailingSlash], method) + m.mux.Handle(fmt.Sprintf("%s %s", method, withTrailingSlash), h) } // ServeHTTP implements the [http.Handler] interface. diff --git a/rest/mux/mux_test.go b/rest/mux/mux_test.go index 7acb43c..a282b2d 100644 --- a/rest/mux/mux_test.go +++ b/rest/mux/mux_test.go @@ -7,11 +7,9 @@ package mux import ( "encoding/json" - "fmt" "io" "net/http" "net/http/httptest" - "path" "testing" "github.com/stretchr/testify/assert" @@ -92,7 +90,7 @@ func TestNotFoundHandler(t *testing.T) { w := httptest.NewRecorder() r := httptest.NewRequest( http.MethodGet, - fmt.Sprintf("http://%s", path.Join("example.com", testCase.RequestPath)), + "http://example.com"+testCase.RequestPath, nil, ) @@ -189,7 +187,7 @@ func TestMethodNotAllowedHandler(t *testing.T) { w := httptest.NewRecorder() r := httptest.NewRequest( string(testCase.Method), - fmt.Sprintf("http://%s", path.Join("example.com", testCase.RequestPath)), + "http://example.com"+testCase.RequestPath, nil, )