fix host script

This commit is contained in:
Matthieu Jolimaitre 2024-05-14 22:36:11 +02:00
parent bccb40e8e7
commit 52cc33f807

View file

@ -4,18 +4,17 @@ async function main() {
const [program_path] = Deno.args; const [program_path] = Deno.args;
if (program_path === undefined) fail_with("Usage: host.ts <program_path>"); if (program_path === undefined) fail_with("Usage: host.ts <program_path>");
const port = 1728; const port = 1728;
const server = Deno.listen({ port }); const server = Deno.serve({ port }, () => handle(program_path));
console.log("listening on port", port); await server.finished;
for await (const connection of server) handle(connection, program_path);
} }
async function handle(connection: Deno.TcpConn, program_path: string) { async function handle(program_path: string) {
console.log("serving"); console.log("Serving", program_path);
const file = await try_else( const file = await try_else(
() => Deno.open(program_path, { read: true }), () => Deno.open(program_path, { read: true }),
() => fail_with("Program at", program_path, "does not exists"), () => fail_with("Program at", program_path, "does not exists"),
); );
await try_(() => file.readable.pipeTo(connection.writable)); return new Response(file.readable);
} }
function fail_with(...message: string[]) { function fail_with(...message: string[]) {
@ -31,8 +30,4 @@ async function try_else<T>(operation: () => T | Promise<T>, on_error: (error: un
} }
} }
async function try_<T>(operation: () => T | Promise<T>) {
return await try_else(operation, () => null);
}
if (import.meta.main) await main(); if (import.meta.main) await main();