Use RoutePath in URLFormat middleware (#718)
This commit is contained in:
parent
42a41a8f67
commit
0fe6bf1ba3
2 changed files with 24 additions and 1 deletions
|
|
@ -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:], ".")
|
||||
|
|
@ -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]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue