diff --git a/README.md b/README.md new file mode 100644 index 0000000..f526a10 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# hatsune-2025-stats + +use [Deno](https://deno.com/) to run + +merry new year \ No newline at end of file diff --git a/deno.json b/deno.json index cd46086..239114c 100644 --- a/deno.json +++ b/deno.json @@ -1,6 +1,6 @@ { "tasks": { - "dev": "deno run -A main.ts" + "dev": "deno run --allow-read=./ --allow-net main.ts" }, "imports": { "@std/assert": "jsr:@std/assert@1", diff --git a/main.ts b/main.ts index 2b99fa1..1bcbec6 100644 --- a/main.ts +++ b/main.ts @@ -1,42 +1,54 @@ -import { contentType } from "@std/media-types"; import path from "node:path"; const NET_PORT = 4536; const NET_HOST = '10.0.1.39'; const WEB_ROOT = './res/'; +interface FileMapping { + endpoints: string[], + path: string, + mime: string +} + +const mappings: FileMapping[] = [ + { + endpoints: ['/', '/index.html'], + path: "/index.html", + mime: "text/html" + }, + { + endpoints: ['/style.css'], + path: "/style.css", + mime: "text/css" + } +] as const; + Deno.serve({ hostname: NET_HOST, port: NET_PORT, onListen: addr => console.log(`Listening on http://${addr.hostname}:${addr.port}`) }, req => { + const notFound = new Response("Not Found. Did you try thinking Miku?", { + status: 404, + statusText: "Not Found (oo-ee-oo)", + headers: { "Content-Type": "text/plain" } + }); + const url = new URL(req.url); if (url.pathname == '/') url.pathname = '/index.html'; - + + const mapping = mappings.find(val => val.endpoints.some(val => url.pathname === val)); + + console.log(`${req.method} ${url.pathname} | mapping exists: ${typeof mapping !== 'undefined'}`); return new Promise(resolve => { - Deno.readFile(path.join(WEB_ROOT, url.pathname)).then(data => { - - const pathParts = url.pathname.split('/'); - const lastPart = pathParts[pathParts.length - 1]; - const extensionParts = lastPart.split('.'); - const extension = extensionParts[extensionParts.length - 1]; - - const mime = contentType(extension); - if (!mime) throw new Error("No mime-type found"); - - console.log(`${req.method} ${url}`); - resolve(new Response(data, { headers: { "Content-Type": mime }})) - - }).catch(() => { - - console.log(`404 ${req.method} ${url}`); - resolve(new Response("Not Found. Did you try thinking Miku?", { - status: 404, - statusText: "Not Found (oo-ee-oo)", - headers: { "Content-Type": "text/plain" } - })); - - }); - }) + if (mapping) { + Deno.readFile(path.join(WEB_ROOT, mapping.path)).then(data => { + resolve(new Response(data, { headers: { "Content-Type": mapping.mime }})); + }).catch(reason => { + console.error(reason); + resolve(notFound); + }); + } else resolve(notFound); + }); }); \ No newline at end of file