Compare commits

..

No commits in common. "7007a2c9943c6ee3a1476da6eed8bc74eac18648" and "bccb40e8e7d5c3ea020b972fa1d7da862bbe3345" have entirely different histories.

2 changed files with 28 additions and 29 deletions

View file

@ -1,30 +1,38 @@
#!/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 }, (request) => handle(request)); const server = Deno.listen({ port });
await server.finished; console.log("listening on port", port);
for await (const connection of server) handle(connection, program_path);
} }
async function handle(request: Request) { async function handle(connection: Deno.TcpConn, program_path: string) {
const script = await open_requested_script(request); console.log("serving");
if (script instanceof Response) return script; const file = await try_else(
console.log("Serving", script.path); () => Deno.open(program_path, { read: true }),
return new Response(script.content.readable); () => fail_with("Program at", program_path, "does not exists"),
);
await try_(() => file.readable.pipeTo(connection.writable));
} }
async function open_requested_script(request: Request) { function fail_with(...message: string[]) {
const requested_path = new URL(request.url).pathname.slice(1); console.error(...message);
const invalid = () => new Response("Invalid script.", { status: 400 }); return Deno.exit(1);
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 {
const path = "./scripts/" + requested_path + ".lua"; return await operation();
const content = await Deno.open(path, { read: true }); } catch (error) {
return { path, content }; return await on_error(error);
} catch (_) {
return new Response("Unknown script.", { status: 400 });
} }
} }
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();

View file

@ -1,17 +1,8 @@
local path = ... local arg1, arg2, arg3 = ...
local function main() local function main()
if path == nil then print("arg1", arg1, "arg2", arg2, "arg3", arg3)
print("Usage: cat <path>") local file = fs.open()
return
end
local file = fs.open(path, "r")
if file == nil then
print("No such file:", path)
return
end
local content = file.readAll()
print(content)
end end
main() main()