feat: add static file support (#58)

This commit adds support for serving static files. Static can be placed
into the `/static` directory (as a sibling of the `/pages` directory).
This commit is contained in:
Luca Casonato
2021-09-25 13:37:46 +02:00
committed by GitHub
parent a25ec7109c
commit 75afa6daca
9 changed files with 117 additions and 35 deletions
+1
View File
@@ -1,5 +1,6 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
+1 -1
View File
@@ -1,4 +1,4 @@
import { start } from "../server.ts";
import routes from "./routes.gen.ts";
start(routes);
await start(routes);
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+2 -1
View File
@@ -141,13 +141,14 @@ export const handler = (_req: Request): Response => {
const serverUrl = new URL("../../server.ts", import.meta.url);
const MAIN_TS = `/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
import { start } from "${serverUrl}";
import routes from "./routes.gen.ts";
start(routes);
await start(routes);
`;
await Deno.writeTextFile(
join(directory, "main.ts"),
+96 -5
View File
@@ -1,4 +1,11 @@
import { extname, mediaTypeLookup, router } from "./deps.ts";
import {
extname,
fromFileUrl,
mediaTypeLookup,
router,
toFileUrl,
walk,
} from "./deps.ts";
import { Routes } from "./mod.ts";
import { Bundler } from "./bundle.ts";
import { INTERNAL_PREFIX } from "./constants.ts";
@@ -15,11 +22,17 @@ import { render as internalRender } from "./render.tsx";
export class ServerContext {
#pages: Page[];
#staticFiles: [URL, string][];
#bundler: Bundler;
#renderer: Renderer;
constructor(pages: Page[], renderer: Renderer) {
constructor(
pages: Page[],
staticFiles: [URL, string][],
renderer: Renderer,
) {
this.#pages = pages;
this.#staticFiles = staticFiles;
this.#renderer = renderer;
this.#bundler = new Bundler(pages);
}
@@ -27,7 +40,7 @@ export class ServerContext {
/**
* Process the routes into individual components and pages.
*/
static fromRoutes(routes: Routes): ServerContext {
static async fromRoutes(routes: Routes): Promise<ServerContext> {
// Get the routes' base URL.
const baseUrl = new URL("./", routes.baseUrl).href;
@@ -74,16 +87,55 @@ export class ServerContext {
}
sortRoutes(pages);
return new ServerContext(pages, renderer);
const staticFiles: [URL, string][] = [];
try {
const staticFolder = new URL("./static", routes.baseUrl);
// TODO(lucacasonato): remove the extranious Deno.readDir when
// https://github.com/denoland/deno_std/issues/1310 is fixed.
for await (const _ of Deno.readDir(fromFileUrl(staticFolder))) {
// do nothing
}
const entires = walk(fromFileUrl(staticFolder), {
includeFiles: true,
includeDirs: false,
followSymlinks: false,
});
for await (const entry of entires) {
const path = toFileUrl(entry.path);
const subpath = path.href.substring(staticFolder.href.length);
staticFiles.push([path, subpath]);
}
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
// Do nothing.
} else {
throw err;
}
}
return new ServerContext(pages, staticFiles, renderer);
}
/**
* This functions returns a request handler that handles all routes required
* by fresh, including static files.
*/
handler(): router.RequestHandler {
return router.router(this.#routes());
}
/**
* This function returns all routes required by fresh as an extended
* path-to-regex, to handler mapping.
*/
routes(): router.Routes {
#routes(): router.Routes {
const routes: router.Routes = {};
// Add the static file routes.
for (const [fullPath, path] of this.#staticFiles) {
const route = sanitizePathToRegex(path);
routes[`GET@${route}`] = this.#staticFileHandler(fullPath);
}
for (const page of this.#pages) {
const bundlePath = `/${page.name}.js`;
const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : [];
@@ -135,6 +187,22 @@ export class ServerContext {
return routes;
}
#staticFileHandler(fullPath: URL): router.MatchHandler {
return async (_req: Request) => {
try {
const data = await Deno.readFile(fullPath);
const contentType = mediaTypeLookup(extname(fullPath.href)) ??
"application/octet-stream";
return new Response(data, { headers: { "content-type": contentType } });
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return new Response("404 Not Found", { status: 404 });
}
throw err;
}
};
}
/**
* Returns a router that contains all fresh routes. Should be mounted at
* constants.INTERNAL_PREFIX
@@ -219,3 +287,26 @@ function pathToRoute(path: string): string {
.join("/");
return route;
}
// Normalize a path for use in a URL. Returns null if the path is unparsable.
export function normalizeURLPath(path: string): string | null {
try {
const pathUrl = new URL("file:///");
pathUrl.pathname = path;
return pathUrl.pathname;
} catch {
return null;
}
}
function sanitizePathToRegex(path: string): string {
return path
.replaceAll("\*", "\\*")
.replaceAll("\+", "\\+")
.replaceAll("\?", "\\?")
.replaceAll("\{", "\\{")
.replaceAll("\}", "\\}")
.replaceAll("\(", "\\(")
.replaceAll("\)", "\\)")
.replaceAll("\:", "\\:");
}
+7 -1
View File
@@ -2,7 +2,13 @@
export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.14";
// -- std --
export { extname } from "https://deno.land/std@0.108.0/path/mod.ts";
export {
extname,
fromFileUrl,
toFileUrl,
} from "https://deno.land/std@0.108.0/path/mod.ts";
export { walk } from "https://deno.land/std@0.108.0/fs/walk.ts";
export { listenAndServe } from "https://deno.land/std@0.108.0/http/server.ts";
// -- router --
export * as router from "https://crux.land/router@0.0.4";
+6 -24
View File
@@ -1,5 +1,5 @@
import { ServerContext } from "./context.ts";
import { router } from "./deps.ts";
import { listenAndServe } from "./deps.ts";
import { PageModule, RendererModule } from "./types.ts";
export type { Handler, HandlerContext, Handlers } from "./types.ts";
export { RenderContext } from "./render.tsx";
@@ -10,28 +10,10 @@ export interface Routes {
baseUrl: string;
}
export { router, ServerContext };
export { ServerContext };
export function start(routes: Routes) {
const ctx = ServerContext.fromRoutes(routes);
const app = router.router(ctx.routes());
serve(app);
}
async function serve(handler: (req: Request) => Response | Promise<Response>) {
async function handleConn(conn: Deno.Conn) {
const httpConn = Deno.serveHttp(conn);
for await (const e of httpConn) {
e.respondWith(handler(e.request))
.catch((e) => console.error("Failed handing a request:", e));
}
}
const listener = Deno.listen({ port: 8000 });
const addr = listener.addr as Deno.NetAddr;
console.log(`Listening on http://${addr.hostname}:${addr.port}`);
for await (const conn of listener) {
handleConn(conn)
.catch((e) => console.error("Failed serving a connection:", e));
}
export async function start(routes: Routes) {
const ctx = await ServerContext.fromRoutes(routes);
console.log("Server listening on http://localhost:8000");
await listenAndServe(":8000", ctx.handler());
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { start } from "../../server.ts";
import routes from "./routes.gen.ts";
start(routes);
await start(routes);
+3 -2
View File
@@ -1,8 +1,9 @@
import { router as r, ServerContext } from "../server.ts";
import { ServerContext } from "../server.ts";
import { assert, assertEquals, assertStringIncludes } from "./deps.ts";
import routes from "./fixture/routes.gen.ts";
const router = r.router(ServerContext.fromRoutes(routes).routes());
const ctx = await ServerContext.fromRoutes(routes);
const router = ctx.handler();
Deno.test("/ page prerender", async () => {
const resp = await router(new Request("https://fresh.deno.dev/"));