33 lines
904 B
TypeScript
Executable file
33 lines
904 B
TypeScript
Executable file
#!/bin/env -S deno run --allow-read --allow-net
|
|
|
|
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.serve({ port }, () => handle(program_path));
|
|
await server.finished;
|
|
}
|
|
|
|
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"),
|
|
);
|
|
return new Response(file.readable);
|
|
}
|
|
|
|
function fail_with(...message: string[]) {
|
|
console.error(...message);
|
|
return Deno.exit(1);
|
|
}
|
|
|
|
async function try_else<T>(operation: () => T | Promise<T>, on_error: (error: unknown) => T | Promise<T>) {
|
|
try {
|
|
return await operation();
|
|
} catch (error) {
|
|
return await on_error(error);
|
|
}
|
|
}
|
|
|
|
if (import.meta.main) await main();
|