Skip to content

Commit 0fe6bf1

Browse files
authored
Use RoutePath in URLFormat middleware (#718)
1 parent 42a41a8 commit 0fe6bf1

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

middleware/url_format.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ func URLFormat(next http.Handler) http.Handler {
5151
var format string
5252
path := r.URL.Path
5353

54+
rctx := chi.RouteContext(r.Context())
55+
if rctx != nil && rctx.RoutePath != "" {
56+
path = rctx.RoutePath
57+
}
58+
5459
if strings.Index(path, ".") > 0 {
5560
base := strings.LastIndex(path, "/")
5661
idx := strings.LastIndex(path[base:], ".")
@@ -59,7 +64,6 @@ func URLFormat(next http.Handler) http.Handler {
5964
idx += base
6065
format = path[idx+1:]
6166

62-
rctx := chi.RouteContext(r.Context())
6367
rctx.RoutePath = path[:idx]
6468
}
6569
}

middleware/url_format_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,22 @@ func TestURLFormat(t *testing.T) {
4848
t.Fatalf(resp)
4949
}
5050
}
51+
52+
func TestURLFormatInSubRouter(t *testing.T) {
53+
r := chi.NewRouter()
54+
55+
r.Route("/articles/{articleID}", func(r chi.Router) {
56+
r.Use(URLFormat)
57+
r.Get("/subroute", func(w http.ResponseWriter, r *http.Request) {
58+
articleID := chi.URLParam(r, "articleID")
59+
w.Write([]byte(articleID))
60+
})
61+
})
62+
63+
ts := httptest.NewServer(r)
64+
defer ts.Close()
65+
66+
if _, resp := testRequest(t, ts, "GET", "/articles/1/subroute.json", nil); resp != "1" {
67+
t.Fatalf(resp)
68+
}
69+
}

0 commit comments

Comments
 (0)