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
+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());
}