Skip to content

Commit

Permalink
Use RoutePath in URLFormat middleware (#718)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kazetsukai committed Oct 27, 2022
1 parent 42a41a8 commit 0fe6bf1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 5 additions & 1 deletion middleware/url_format.go
Expand Up @@ -51,6 +51,11 @@ func URLFormat(next http.Handler) http.Handler {
var format string
path := r.URL.Path

rctx := chi.RouteContext(r.Context())
if rctx != nil && rctx.RoutePath != "" {
path = rctx.RoutePath
}

if strings.Index(path, ".") > 0 {
base := strings.LastIndex(path, "/")
idx := strings.LastIndex(path[base:], ".")
Expand All @@ -59,7 +64,6 @@ func URLFormat(next http.Handler) http.Handler {
idx += base
format = path[idx+1:]

rctx := chi.RouteContext(r.Context())
rctx.RoutePath = path[:idx]
}
}
Expand Down
19 changes: 19 additions & 0 deletions middleware/url_format_test.go
Expand Up @@ -48,3 +48,22 @@ func TestURLFormat(t *testing.T) {
t.Fatalf(resp)
}
}

func TestURLFormatInSubRouter(t *testing.T) {
r := chi.NewRouter()

r.Route("/articles/{articleID}", func(r chi.Router) {
r.Use(URLFormat)
r.Get("/subroute", func(w http.ResponseWriter, r *http.Request) {
articleID := chi.URLParam(r, "articleID")
w.Write([]byte(articleID))
})
})

ts := httptest.NewServer(r)
defer ts.Close()

if _, resp := testRequest(t, ts, "GET", "/articles/1/subroute.json", nil); resp != "1" {
t.Fatalf(resp)
}
}

0 comments on commit 0fe6bf1

Please sign in to comment.