feat(server): trailing slash configuration (#1291)

This commit is contained in:
Reed von Redwitz
2023-06-15 19:01:07 +02:00
committed by GitHub
parent 80306563d2
commit f5f8928c89
8 changed files with 106 additions and 1 deletions
+19 -1
View File
@@ -33,6 +33,7 @@ import {
RenderOptions,
Route,
RouteModule,
RouterOptions,
UnknownPage,
UnknownPageModule,
} from "./types.ts";
@@ -86,6 +87,7 @@ export class ServerContext {
#error: ErrorPage;
#plugins: Plugin[];
#builder: Builder | Promise<BuildSnapshot> | BuildSnapshot;
#routerOptions: RouterOptions;
constructor(
routes: Route[],
@@ -100,6 +102,7 @@ export class ServerContext {
configPath: string,
jsxConfig: JSXConfig,
dev: boolean = isDevMode(),
routerOptions: RouterOptions,
) {
this.#routes = routes;
this.#islands = islands;
@@ -118,6 +121,7 @@ export class ServerContext {
dev: this.#dev,
jsxConfig,
});
this.#routerOptions = routerOptions;
}
/**
@@ -345,6 +349,7 @@ export class ServerContext {
configPath,
jsxConfig,
dev,
opts.router ?? DEFAULT_ROUTER_OPTIONS,
);
}
@@ -359,12 +364,16 @@ export class ServerContext {
this.#middlewares,
handlers.errorHandler,
);
const trailingSlashEnabled = this.#routerOptions?.trailingSlash;
return async function handler(req: Request, connInfo: ConnInfo) {
// 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("/")) {
if (
url.pathname.length > 1 && url.pathname.endsWith("/") &&
!trailingSlashEnabled
) {
// Remove trailing slashes
const path = url.pathname.replace(/\/+$/, "");
const location = `${path}${url.search}`;
@@ -372,6 +381,8 @@ export class ServerContext {
status: Status.TemporaryRedirect,
headers: { location },
});
} else if (trailingSlashEnabled && !url.pathname.endsWith("/")) {
return Response.redirect(url.href + "/", Status.PermanentRedirect);
}
return await withMiddlewares(req, connInfo, inner);
@@ -606,6 +617,9 @@ export class ServerContext {
const createUnknownRender = genRender(this.#notFound, Status.NotFound);
for (const route of this.#routes) {
if (this.#routerOptions.trailingSlash && route.pattern != "/") {
route.pattern += "/";
}
const createRender = genRender(route, Status.OK);
if (typeof route.handler === "function") {
routes[route.pattern] = {
@@ -778,6 +792,10 @@ const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
};
const DEFAULT_ROUTER_OPTIONS: RouterOptions = {
trailingSlash: false,
};
const DEFAULT_APP: AppModule = {
default: ({ Component }) => h(Component, {}),
};
+9
View File
@@ -19,6 +19,15 @@ export interface FreshOptions {
render?: RenderFunction;
plugins?: Plugin[];
staticDir?: string;
router?: RouterOptions;
}
export interface RouterOptions {
/**
* Controls whether Fresh will append a trailing slash to the URL.
* @default {false}
*/
trailingSlash?: boolean;
}
export type RenderFunction = (
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env -S deno run -A --watch=static/,routes/
import dev from "$fresh/dev.ts";
await dev(import.meta.url, "./main.ts");
+17
View File
@@ -0,0 +1,17 @@
// DO NOT EDIT. This file is generated by fresh.
// This file SHOULD be checked into source version control.
// This file is automatically updated during development when running `dev.ts`.
import * as $0 from "./routes/about.tsx";
import * as $1 from "./routes/index.tsx";
const manifest = {
routes: {
"./routes/about.tsx": $0,
"./routes/index.tsx": $1,
},
islands: {},
baseUrl: import.meta.url,
};
export default manifest;
+10
View File
@@ -0,0 +1,10 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "$fresh/server.ts";
import manifest from "./fresh.gen.ts";
await start(manifest);
+7
View File
@@ -0,0 +1,7 @@
export default function About() {
return (
<div>
About
</div>
);
}
+7
View File
@@ -0,0 +1,7 @@
export default function Home() {
return (
<div>
Hello
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { ServerContext, Status } from "../server.ts";
import { assert, assertEquals } from "./deps.ts";
import manifest from "./fixture_router/fresh.gen.ts";
const ctx = await ServerContext.fromManifest(manifest, {
router: {
trailingSlash: true,
},
});
const router = (req: Request) => {
return ctx.handler()(req, {
localAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
remoteAddr: {
transport: "tcp",
hostname: "127.0.0.1",
port: 80,
},
});
};
Deno.test("forwards slash placed at the end of url", async () => {
const targetUrl = "https://fresh.deno.dev/about";
const resp = await router(new Request(targetUrl));
assert(resp);
assertEquals(resp.status, Status.PermanentRedirect);
// forwarded location should be with trailing slash
assertEquals(resp.headers.get("location"), targetUrl + "/");
});