1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-26 09:10:40 -05:00
Original: c8e5d98900
This commit is contained in:
Bartek Iwańczuk 2018-12-09 21:35:26 +01:00 committed by Ryan Dahl
parent 2b360c60a5
commit 2b1733e936
2 changed files with 42 additions and 8 deletions

40
file_server.ts Normal file → Executable file
View file

@ -1,18 +1,44 @@
#!/usr/bin/env deno --allow-net
// This program serves files in the current directory over HTTP.
// TODO Supply the directory to serve as a CLI argument.
// 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
import { listenAndServe } from "./http.ts"; import { listenAndServe } from "./http.ts";
import { open, cwd } from "deno"; import { cwd, readFile, DenoError, ErrorKind } from "deno";
const addr = "0.0.0.0:4500"; const addr = "0.0.0.0:4500";
const d = cwd(); const currentDir = cwd();
const encoder = new TextEncoder();
listenAndServe(addr, async req => { listenAndServe(addr, async req => {
const filename = d + "/" + req.url; const fileName = req.url.replace(/\/$/, '/index.html');
let res; const filePath = currentDir + fileName;
let file;
try { try {
res = { status: 200, body: open(filename) }; file = await readFile(filePath);
} catch (e) { } catch (e) {
res = { status: 500, body: "bad" }; if (e instanceof DenoError && e.kind === ErrorKind.NotFound) {
await req.respond({ status: 404, body: encoder.encode("Not found") });
} else {
await req.response({ status: 500, body: encoder.encode("Internal server error") });
} }
req.respond(res); return;
}
const headers = new Headers();
headers.set('content-type', 'octet-stream');
const res = {
status: 200,
body: file,
headers,
}
await req.respond(res);
}); });
console.log(`HTTP server listening on http://${addr}/`); console.log(`HTTP server listening on http://${addr}/`);

View file

@ -82,6 +82,14 @@ export async function* serve(addr: string) {
listener.close(); listener.close();
} }
export async function listenAndServe(addr: string, handler: (ServerRequest) => void) {
const server = serve(addr);
for await (const request of server) {
await handler(request);
}
}
interface Response { interface Response {
status?: number; status?: number;
headers?: Headers; headers?: Headers;