fix host script

This commit is contained in:
Matthieu Jolimaitre 2024-05-15 00:33:42 +02:00
parent 52cc33f807
commit 62cd230d5b

View file

@ -1,32 +1,29 @@
#!/bin/env -S deno run --allow-read --allow-net #!/bin/env -S deno run --allow-read --allow-net
async function main() { async function main() {
const [program_path] = Deno.args;
if (program_path === undefined) fail_with("Usage: host.ts <program_path>");
const port = 1728; const port = 1728;
const server = Deno.serve({ port }, () => handle(program_path)); const server = Deno.serve({ port }, (request) => handle(request));
await server.finished; await server.finished;
} }
async function handle(program_path: string) { async function handle(request: Request) {
console.log("Serving", program_path); const script = await open_requested_script(request);
const file = await try_else( if (script instanceof Response) return script;
() => Deno.open(program_path, { read: true }), console.log("Serving", script.path);
() => fail_with("Program at", program_path, "does not exists"), return new Response(script.content.readable);
);
return new Response(file.readable);
} }
function fail_with(...message: string[]) { async function open_requested_script(request: Request) {
console.error(...message); const requested_path = new URL(request.url).pathname.slice(1);
return Deno.exit(1); const invalid = () => new Response("Invalid script.", { status: 400 });
} if (requested_path.includes("/")) return invalid();
if (requested_path.includes(".")) return invalid();
async function try_else<T>(operation: () => T | Promise<T>, on_error: (error: unknown) => T | Promise<T>) {
try { try {
return await operation(); const path = "./scripts/" + requested_path + ".lua";
} catch (error) { const content = await Deno.open(path, { read: true });
return await on_error(error); return { path, content };
} catch (_) {
return new Response("Unknown script.", { status: 400 });
} }
} }