Skip to content

Commit cdfef4d

Browse files
committed
fix: correct approach
1 parent 7340fb9 commit cdfef4d

File tree

2 files changed

+23
-10
lines changed

2 files changed

+23
-10
lines changed

coderd/coderd.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -1749,10 +1749,12 @@ func singleSlashMW(next http.Handler) http.Handler {
17491749
newPath := multipleSlashesRe.ReplaceAllString(path, "/")
17501750

17511751
// Apply the cleaned path
1752+
// The approach is consistent with: https://github.com/go-chi/chi/blob/e846b8304c769c4f1a51c9de06bebfaa4576bd88/middleware/strip.go#L24-L28
17521753
if rctx != nil {
17531754
rctx.RoutePath = newPath
1755+
} else {
1756+
r.URL.Path = newPath
17541757
}
1755-
r.URL.Path = newPath
17561758

17571759
next.ServeHTTP(w, r)
17581760
}

coderd/coderd_internal_test.go

+20-9
Original file line numberDiff line numberDiff line change
@@ -33,26 +33,37 @@ func TestStripSlashesMW(t *testing.T) {
3333

3434
for _, tt := range tests {
3535
tt := tt
36-
t.Run(tt.name, func(t *testing.T) {
37-
t.Parallel()
3836

37+
t.Run("chi/"+tt.name, func(t *testing.T) {
38+
t.Parallel()
3939
req := httptest.NewRequest("GET", tt.inputPath, nil)
4040
rec := httptest.NewRecorder()
4141

42-
// Create a chi RouteContext and attach it to the request
42+
// given
4343
rctx := chi.NewRouteContext()
44-
rctx.RoutePath = tt.inputPath // Simulate chi route path
44+
rctx.RoutePath = tt.inputPath
4545
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
4646

47-
// Pass the request through the middleware
47+
// when
4848
singleSlashMW(handler).ServeHTTP(rec, req)
49-
50-
// Get the updated chi RouteContext after middleware processing
5149
updatedCtx := chi.RouteContext(req.Context())
5250

53-
// Validate URL path
54-
assert.Equal(t, tt.wantPath, req.URL.Path)
51+
// then
52+
assert.Equal(t, tt.inputPath, req.URL.Path)
5553
assert.Equal(t, tt.wantPath, updatedCtx.RoutePath)
5654
})
55+
56+
t.Run("stdlib/"+tt.name, func(t *testing.T) {
57+
t.Parallel()
58+
req := httptest.NewRequest("GET", tt.inputPath, nil)
59+
rec := httptest.NewRecorder()
60+
61+
// when
62+
singleSlashMW(handler).ServeHTTP(rec, req)
63+
64+
// then
65+
assert.Equal(t, tt.wantPath, req.URL.Path)
66+
assert.Nil(t, chi.RouteContext(req.Context()))
67+
})
5768
}
5869
}

0 commit comments

Comments
 (0)