Created
April 10, 2022 04:40
-
-
Save tani/017d486e4c012cbbbe8e68ec17446d19 to your computer and use it in GitHub Desktop.
This file contains 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 pandoc from "https://cdn.jsdelivr.net/gh/tani/deno-pandoc/out/mod.js"; | |
import * as MediaType from "https://deno.land/x/media_types@v2.3.7/mod.ts"; | |
import * as Eta from "https://deno.land/x/eta@v1.12.3/mod.ts"; | |
import * as Yaml from "https://deno.land/std@0.114.0/encoding/yaml.ts"; | |
import { serve } from "https://deno.land/std@0.114.0/http/server.ts"; | |
const { pathname: dirname } = new URL('.', import.meta.url) | |
async function handleRequest(request: Request): Promise<Response> { | |
const { pathname } = new URL(request.url) | |
const relativePathname = dirname + pathname.slice(1) | |
try { | |
const blob = await Deno.readFile(relativePathname) | |
const contentType = MediaType.lookup(relativePathname) ?? 'text/plain' | |
const options = { headers: { 'content-type': contentType } } | |
return new Response(blob, options) | |
} catch { | |
try { | |
const text = await Deno.readTextFile(relativePathname + '.md') | |
const yaml = text.replace(/----+/, '').replace(/----+[\s\S]*/, '') | |
const header = Yaml.parse(yaml) as Record<string, unknown> | |
try { | |
const layout = await Deno.readTextFile(dirname + header.layout + '.ejs') | |
const markdown = text.replace(/----+[\s\S]+?----+/, '') | |
const content = pandoc(markdown) | |
const html = await Eta.render(layout, { ...header, content }) | |
const options = { headers: { 'content-type': 'text/html' } } | |
return new Response(html as string, options ) | |
} catch (err) { | |
return new Response('', { status: 500 }) | |
} | |
} catch { | |
return new Response('', { status: 404 }) | |
} | |
} | |
} | |
serve(handleRequest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment