feat: redirect trailing slash to non-trailing counterpart (#78)
This commit is contained in:
@@ -142,6 +142,14 @@ export class ServerContext {
|
||||
const inner = router.router(this.#routes());
|
||||
const middleware = this.#middleware;
|
||||
return function handler(req: Request) {
|
||||
// Redirect requests that end with a trailing slash
|
||||
// to their non-trailing slash counterpart.
|
||||
// Ex: /about/ -> /about
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname.length > 1 && url.pathname.endsWith("/")) {
|
||||
url.pathname = url.pathname.slice(0, -1);
|
||||
return Response.redirect(url, 307);
|
||||
}
|
||||
const handle = () => Promise.resolve(inner(req));
|
||||
return middleware.handler(req, handle);
|
||||
};
|
||||
|
||||
@@ -139,3 +139,13 @@ Deno.test("/books/:id page - /books/abc", async () => {
|
||||
assert(resp);
|
||||
assertEquals(resp.status, 404);
|
||||
});
|
||||
|
||||
Deno.test("redirect /pages/fresh/ to /pages/fresh", async () => {
|
||||
const resp = await router(new Request("https://fresh.deno.dev/pages/fresh/"));
|
||||
assert(resp);
|
||||
assertEquals(resp.status, 307);
|
||||
assertEquals(
|
||||
resp.headers.get("location"),
|
||||
"https://fresh.deno.dev/pages/fresh",
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user