Skip to content

Instantly share code, notes, and snippets.

@cablehead
Created September 27, 2024 01:35
Show Gist options
  • Save cablehead/441ac3667319f1d1c3f1e652dc4cb8ff to your computer and use it in GitHub Desktop.
Save cablehead/441ac3667319f1d1c3f1e652dc4cb8ff to your computer and use it in GitHub Desktop.
hono.localhost
import { Hono } from "jsr:@hono/hono";
const app = new Hono();
app.get("/", async (c) => {
try {
const indexHtml = await Deno.readTextFile("./index.html");
return c.html(indexHtml);
} catch (error) {
return c.text("Error loading index.html", 500);
}
});
app.get("/sse", async (c) => {
const upstreamResponse = await fetch("http://localhost:3033?follow");
if (!upstreamResponse.body) {
return c.text("Failed to read response stream", 500);
}
const reader = upstreamResponse.body.getReader();
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = new TextDecoder().decode(value);
const lines = text.split("\n");
for (const line of lines) {
if (line.trim()) {
controller.enqueue(encoder.encode(`data: ${line}\n\n`));
}
}
}
} catch (error) {
controller.error(error);
} finally {
controller.close();
reader.releaseLock();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
});
});
app.get("/:name", (c) => c.text(`Hello, ${c.params.name}!`));
export default app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment