about summary refs log tree commit diff stats
path: root/src/app.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/app.ts')
-rw-r--r--src/app.ts42
1 files changed, 34 insertions, 8 deletions
diff --git a/src/app.ts b/src/app.ts
index 727ec2f..57ae71d 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -3,17 +3,17 @@ import fs, { Stats } from "node:fs";
 import type { BunFile, Serve } from "bun";
 import * as Sentry from "@sentry/node";
 import prom from "bun-prometheus-client";
+import log from "loglevel";
 
-import readConfig from "./config";
+import config from "./config";
+
+log.setLevel((Bun.env.LOG_LEVEL || "info") as log.LogLevelDesc);
 
 Sentry.init({
   release: `homestead@${Bun.env.FLY_MACHINE_VERSION}`,
   tracesSampleRate: 1.0,
 });
 
-const publicDir = "public" + path.sep;
-
-const config = readConfig();
 const defaultHeaders = {
   ...config.extra.headers,
   vary: "Accept-Encoding",
@@ -85,13 +85,14 @@ function walkDirectory(root: string, dir: string) {
         if (dir !== "") {
           registerFile(relPath, dir + path.sep, absPath, stat);
         }
+      } else {
+        registerFile(relPath, relPath, absPath, stat);
       }
-      registerFile(relPath, relPath, absPath, stat);
     }
   }
 }
 
-walkDirectory(publicDir, "");
+walkDirectory("public/", "");
 
 async function serveFile(
   file: File | undefined,
@@ -194,8 +195,22 @@ export const server = {
         }
         transaction.setHttpStatus(200);
         transaction.setTag("http.content-encoding", "identity");
-        return serveFile(file);
+        return serveFile(file, 200, {
+          "content-type": file.type,
+        });
       } else {
+        if (files.has(pathname + "/")) {
+          log.info(`Redirecting to: ${pathname + "/"}`);
+          metrics.requests.inc({
+            method: request.method,
+            path: pathname,
+            status_code: 302,
+          });
+          return new Response("", {
+            status: 302,
+            headers: { location: pathname + "/" },
+          });
+        }
         metrics.requests.inc({
           method: request.method,
           path: pathname,
@@ -203,7 +218,18 @@ export const server = {
         });
         transaction.setHttpStatus(404);
         transaction.setTag("http.content-encoding", "identity");
-        return serveFile(files.get("/404.html"), 404);
+        const notfound = files.get("/404.html");
+        if (notfound) {
+          return serveFile(notfound, 404, {
+            "content-type": "text/html; charset=utf-8",
+          });
+        } else {
+          log.warn("404.html not found");
+          return new Response("404 Not Found", {
+            status: 404,
+            headers: { "content-type": "text/plain", ...defaultHeaders },
+          });
+        }
       }
     } catch (error) {
       transaction.setTag("http.content-encoding", "identity");