Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

middleware: Add strip prefix middleware #875

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions middleware/strip.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,11 @@ func RedirectSlashes(next http.Handler) http.Handler {
}
return http.HandlerFunc(fn)
}

// StripPrefix is a middleware that will strip the provided prefix from the
// request path before handing the request over to the next handler.
func StripPrefix(prefix string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.StripPrefix(prefix, next)
}
}
35 changes: 35 additions & 0 deletions middleware/strip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,38 @@ func TestStripSlashesWithNilContext(t *testing.T) {
t.Fatalf(resp)
}
}

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

r.Use(StripPrefix("/api"))

r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("api root"))
})

r.Get("/accounts", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("api accounts"))
})

r.Get("/accounts/{accountID}", func(w http.ResponseWriter, r *http.Request) {
accountID := chi.URLParam(r, "accountID")
w.Write([]byte(accountID))
})

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

if _, resp := testRequest(t, ts, "GET", "/api/", nil); resp != "api root" {
t.Fatalf("got: %q, want: %q", resp, "api root")
}
if _, resp := testRequest(t, ts, "GET", "/api/accounts", nil); resp != "api accounts" {
t.Fatalf("got: %q, want: %q", resp, "api accounts")
}
if _, resp := testRequest(t, ts, "GET", "/api/accounts/admin", nil); resp != "admin" {
t.Fatalf("got: %q, want: %q", resp, "admin")
}
if _, resp := testRequest(t, ts, "GET", "/api-nope/", nil); resp != "404 page not found\n" {
t.Fatalf("got: %q, want: %q", resp, "404 page not found\n")
}
}