Skip to content

Commit

Permalink
feat(issue-295): register trailing slash and non-trailing slash endpo…
Browse files Browse the repository at this point in the history
…ints to avoid redirects
  • Loading branch information
Zaba505 committed Oct 3, 2024
1 parent 72fcd86 commit f1532f9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
30 changes: 30 additions & 0 deletions rest/mux/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ package mux
import (
"fmt"
"net/http"
"path"
"slices"
"strings"
"sync"
)

Expand Down Expand Up @@ -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.
Expand Down
6 changes: 2 additions & 4 deletions rest/mux/mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ package mux

import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"path"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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,
)

Expand Down Expand Up @@ -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,
)

Expand Down

0 comments on commit f1532f9

Please sign in to comment.