2018-12-09 15:35:26 -05:00
|
|
|
#!/usr/bin/env deno --allow-net
|
|
|
|
|
|
|
|
// This program serves files in the current directory over HTTP.
|
|
|
|
// TODO Stream responses instead of reading them into memory.
|
|
|
|
// TODO Add tests like these:
|
|
|
|
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js
|
|
|
|
|
2018-12-09 20:17:55 -05:00
|
|
|
import { listenAndServe } from "./http";
|
|
|
|
import { cwd, readFile, DenoError, ErrorKind, args } from "deno";
|
2018-11-07 13:16:07 -05:00
|
|
|
|
|
|
|
const addr = "0.0.0.0:4500";
|
2018-12-09 20:17:55 -05:00
|
|
|
let currentDir = cwd();
|
|
|
|
const target = args[1];
|
|
|
|
if (target) {
|
|
|
|
currentDir = `${currentDir}/${target}`;
|
|
|
|
}
|
2018-12-09 15:35:26 -05:00
|
|
|
const encoder = new TextEncoder();
|
|
|
|
|
2018-12-09 20:17:55 -05:00
|
|
|
listenAndServe(addr, async req => {
|
2018-12-09 15:35:26 -05:00
|
|
|
const fileName = req.url.replace(/\/$/, '/index.html');
|
|
|
|
const filePath = currentDir + fileName;
|
|
|
|
let file;
|
2018-11-07 13:16:07 -05:00
|
|
|
|
|
|
|
try {
|
2018-12-09 15:35:26 -05:00
|
|
|
file = await readFile(filePath);
|
2018-11-07 14:17:36 -05:00
|
|
|
} catch (e) {
|
2018-12-09 15:35:26 -05:00
|
|
|
if (e instanceof DenoError && e.kind === ErrorKind.NotFound) {
|
|
|
|
await req.respond({ status: 404, body: encoder.encode("Not found") });
|
|
|
|
} else {
|
2018-12-09 20:17:55 -05:00
|
|
|
await req.respond({ status: 500, body: encoder.encode("Internal server error") });
|
2018-12-09 15:35:26 -05:00
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const headers = new Headers();
|
|
|
|
headers.set('content-type', 'octet-stream');
|
|
|
|
|
|
|
|
const res = {
|
|
|
|
status: 200,
|
|
|
|
body: file,
|
|
|
|
headers,
|
2018-11-07 13:16:07 -05:00
|
|
|
}
|
2018-12-09 15:35:26 -05:00
|
|
|
await req.respond(res);
|
2018-11-07 13:16:07 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
console.log(`HTTP server listening on http://${addr}/`);
|