Compare commits

...

3 commits

Author SHA1 Message Date
7007a2c994 implement cat script 2024-05-15 00:33:54 +02:00
62cd230d5b fix host script 2024-05-15 00:33:42 +02:00
52cc33f807 fix host script 2024-05-14 22:36:11 +02:00
2 changed files with 29 additions and 28 deletions

View file

@ -1,38 +1,30 @@
#!/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.listen({ port }); const server = Deno.serve({ port }, (request) => handle(request));
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(request: Request) {
console.log("serving"); 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);
);
await try_(() => file.readable.pipeTo(connection.writable));
} }
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 });
} }
} }
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,8 +1,17 @@
local arg1, arg2, arg3 = ... local path = ...
local function main() local function main()
print("arg1", arg1, "arg2", arg2, "arg3", arg3) if path == nil then
local file = fs.open() print("Usage: cat <path>")
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()