forked from trackawesomelist/trackawesomelist-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve-markdown.ts
56 lines (54 loc) · 1.69 KB
/
serve-markdown.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { CSS, mustache, path, serve, serveFile } from "./deps.ts";
import {
getDistRepoPath,
getStaticPath,
readTextFile,
urlToFilePath,
} from "./util.ts";
import log from "./log.ts";
import { RunOptions } from "./interface.ts";
import render from "./render-markdown.ts";
export default async function serveSite(runOptions: RunOptions) {
const port = runOptions.port;
const BASE_PATH = getDistRepoPath();
const staticpath = getStaticPath();
const htmlTemplate = await readTextFile("./templates/index.html.mu");
const handler = async (request: Request): Promise<Response> => {
const filepath = urlToFilePath(request.url);
log.debug(`Request for ${filepath}`);
let localPath = BASE_PATH + filepath;
if (!filepath.endsWith(".md")) {
// serve static fold
localPath = path.join(staticpath, filepath);
return await serveFile(request, localPath);
}
// check if file exists
let finalPath: string | undefined;
try {
const fileInfo = Deno.statSync(localPath);
if (fileInfo.isFile) {
finalPath = localPath;
}
} catch (e) {
log.warn(e);
}
if (finalPath) {
const fileContent = await readTextFile(finalPath);
log.debug(`serving file: ${finalPath}`);
const body = render(fileContent);
const htmlContent = mustache.render(htmlTemplate, { CSS, body });
return new Response(htmlContent, {
status: 200,
headers: {
"content-type": "text/html",
},
});
} else {
return Promise.resolve(new Response("Not Found", { status: 404 }));
}
};
log.info(
`HTTP webserver running. Access it at: http://localhost:${port}/`,
);
serve(handler, { port });
}