feat: redirect trailing slash to non-trailing counterpart (#78)

This commit is contained in:
Satya Rohith
2021-11-29 16:03:19 +01:00
committed by GitHub
parent aa1e1bcdb4
commit 489da1b49d
2 changed files with 18 additions and 0 deletions
+8
View File
@@ -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);
};
+10
View File
@@ -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",
);
});