diff --git a/fresh.gen.ts b/fresh.gen.ts index ca60921..b623a72 100644 --- a/fresh.gen.ts +++ b/fresh.gen.ts @@ -4,6 +4,7 @@ import * as $_404 from "./routes/_404.tsx"; import * as $_app from "./routes/_app.tsx"; +import * as $_middleware from "./routes/_middleware.tsx"; import * as $connectivity_test from "./routes/connectivity-test.tsx"; import * as $file_id_analyzer from "./routes/file-id-analyzer.tsx"; import * as $filter_query_browser from "./routes/filter-query-browser.tsx"; @@ -32,6 +33,7 @@ const manifest = { routes: { "./routes/_404.tsx": $_404, "./routes/_app.tsx": $_app, + "./routes/_middleware.tsx": $_middleware, "./routes/connectivity-test.tsx": $connectivity_test, "./routes/file-id-analyzer.tsx": $file_id_analyzer, "./routes/filter-query-browser.tsx": $filter_query_browser, diff --git a/routes/_middleware.tsx b/routes/_middleware.tsx new file mode 100644 index 0000000..90ac092 --- /dev/null +++ b/routes/_middleware.tsx @@ -0,0 +1,47 @@ +import { FreshContext } from "$fresh/server.ts"; + +const HEADER = new TextEncoder().encode(""); + +export async function handler(req: Request, ctx: FreshContext) { + try { + const res = await ctx.next(); + if ( + res.body != null && + res.status == 200 && + res.headers.get("content-type")?.includes("text/html") + ) { + const reader = res.body.getReader(); + let headerSent = false; + const rs = new ReadableStream({ + async pull(controller) { + const result = await reader.read(); + if (result?.done) { + controller.close(); + } else if (result?.value) { + if (!headerSent) { + headerSent = true; + controller.enqueue(HEADER); + return; + } + controller.enqueue(result.value); + } else if (!result) { + controller.error(); + } + }, + async cancel(reason) { + try { + await res.body?.cancel(reason); + } catch { + // + } + }, + }); + return new Response(rs, { headers: res.headers, status: res.status }); + } else { + return res; + } + } catch (err) { + console.trace(err); + } + return Response.redirect(new URL("/", req.url)); +}