Created
September 27, 2024 01:32
-
-
Save cablehead/4a4699cf2df02c338ba25a7067679c71 to your computer and use it in GitHub Desktop.
oak.localhost
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Application, Router } from "https://deno.land/x/oak/mod.ts"; | |
const app = new Application(); | |
const router = new Router(); | |
// Route to serve index.html | |
router.get("/", async (context) => { | |
try { | |
const indexHtml = await Deno.readTextFile("./index.html"); | |
context.response.headers.set("Content-Type", "text/html"); | |
context.response.body = indexHtml; | |
} catch (error) { | |
context.response.status = 500; | |
context.response.body = "Error loading index.html"; | |
} | |
}); | |
// Route for server-sent events (SSE) | |
router.get("/sse", async (context) => { | |
const upstreamResponse = await fetch("http://localhost:3033?follow"); | |
if (!upstreamResponse.body) { | |
context.response.status = 500; | |
context.response.body = "Failed to read response stream"; | |
return; | |
} | |
const reader = upstreamResponse.body.getReader(); | |
const encoder = new TextEncoder(); | |
context.respond = false; // Disable default Oak response handling | |
const body = 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(); | |
} | |
}, | |
}); | |
context.response.headers.set("Content-Type", "text/event-stream"); | |
context.response.headers.set("Cache-Control", "no-cache"); | |
context.response.headers.set("Connection", "keep-alive"); | |
context.response.body = body; | |
}); | |
// Dynamic route for :name | |
router.get("/:name", (context) => { | |
const name = context.params.name; | |
context.response.body = `Hello, ${name}!`; | |
}); | |
// Use the router middleware | |
app.use(router.routes()); | |
app.use(router.allowedMethods()); | |
export default app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment