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;
if (program_path === undefined) fail_with("Usage: host.ts <program_path>");
const port = 1728;
const server = Deno.listen({ port });
console.log("listening on port", port);
for await (const connection of server) handle(connection, program_path);
const server = Deno.serve({ port }, () => handle(program_path));
await server.finished;
}
async function handle(connection: Deno.TcpConn, program_path: string) {
console.log("serving");
async function handle(program_path: string) {
console.log("Serving", program_path);
const file = await try_else(
() => Deno.open(program_path, { read: true }),
() => 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[]) {
@ -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();