|
| 1 | +// routes/og.ts - Dynamic OG image generator |
| 2 | +import { FreshContext } from "fresh"; |
| 3 | + |
| 4 | +export async function handler( |
| 5 | + ctx: FreshContext, |
| 6 | +): Promise<Response> { |
| 7 | + try { |
| 8 | + // Get title from query parameter |
| 9 | + const url = new URL(ctx.req.url); |
| 10 | + const title = url.searchParams.get("title") || ""; |
| 11 | + |
| 12 | + // Read the cover.svg template |
| 13 | + const coverPath = `${Deno.cwd()}/static/images/cover.svg`; |
| 14 | + let svgContent = await Deno.readTextFile(coverPath); |
| 15 | + |
| 16 | + // Replace [[INSERT TITLE]] with the actual title (or empty string for homepage) |
| 17 | + svgContent = svgContent.replace("[[INSERT TITLE]]", title); |
| 18 | + |
| 19 | + // Return the SVG with proper headers |
| 20 | + return new Response(svgContent, { |
| 21 | + headers: { |
| 22 | + "Content-Type": "image/svg+xml", |
| 23 | + "Cache-Control": "public, max-age=31536000, immutable", |
| 24 | + }, |
| 25 | + }); |
| 26 | + } catch (error) { |
| 27 | + console.error("Error generating OG image:", error); |
| 28 | + |
| 29 | + // Fallback to original cover.svg if something goes wrong |
| 30 | + try { |
| 31 | + const coverPath = `${Deno.cwd()}/static/images/cover.svg`; |
| 32 | + const svgContent = await Deno.readTextFile(coverPath); |
| 33 | + return new Response(svgContent, { |
| 34 | + headers: { |
| 35 | + "Content-Type": "image/svg+xml", |
| 36 | + "Cache-Control": "public, max-age=3600", |
| 37 | + }, |
| 38 | + }); |
| 39 | + } catch { |
| 40 | + return new Response("Image not found", { status: 404 }); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
0 commit comments