Skip to content

Commit 5dd7716

Browse files
authored
add strip prefix. (#875)
1 parent 7335050 commit 5dd7716

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

middleware/strip.go

+8
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,11 @@ func RedirectSlashes(next http.Handler) http.Handler {
6060
}
6161
return http.HandlerFunc(fn)
6262
}
63+
64+
// StripPrefix is a middleware that will strip the provided prefix from the
65+
// request path before handing the request over to the next handler.
66+
func StripPrefix(prefix string) func(http.Handler) http.Handler {
67+
return func(next http.Handler) http.Handler {
68+
return http.StripPrefix(prefix, next)
69+
}
70+
}

middleware/strip_test.go

+35
Original file line numberDiff line numberDiff line change
@@ -237,3 +237,38 @@ func TestStripSlashesWithNilContext(t *testing.T) {
237237
t.Fatal(resp)
238238
}
239239
}
240+
241+
func TestStripPrefix(t *testing.T) {
242+
r := chi.NewRouter()
243+
244+
r.Use(StripPrefix("/api"))
245+
246+
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
247+
w.Write([]byte("api root"))
248+
})
249+
250+
r.Get("/accounts", func(w http.ResponseWriter, r *http.Request) {
251+
w.Write([]byte("api accounts"))
252+
})
253+
254+
r.Get("/accounts/{accountID}", func(w http.ResponseWriter, r *http.Request) {
255+
accountID := chi.URLParam(r, "accountID")
256+
w.Write([]byte(accountID))
257+
})
258+
259+
ts := httptest.NewServer(r)
260+
defer ts.Close()
261+
262+
if _, resp := testRequest(t, ts, "GET", "/api/", nil); resp != "api root" {
263+
t.Fatalf("got: %q, want: %q", resp, "api root")
264+
}
265+
if _, resp := testRequest(t, ts, "GET", "/api/accounts", nil); resp != "api accounts" {
266+
t.Fatalf("got: %q, want: %q", resp, "api accounts")
267+
}
268+
if _, resp := testRequest(t, ts, "GET", "/api/accounts/admin", nil); resp != "admin" {
269+
t.Fatalf("got: %q, want: %q", resp, "admin")
270+
}
271+
if _, resp := testRequest(t, ts, "GET", "/api-nope/", nil); resp != "404 page not found\n" {
272+
t.Fatalf("got: %q, want: %q", resp, "404 page not found\n")
273+
}
274+
}

0 commit comments

Comments
 (0)