Skip to content

Commit

Permalink
Simple file server (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
bartlomieju authored and ry committed Dec 9, 2018
1 parent 0e82a42 commit c8e5d98
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
42 changes: 34 additions & 8 deletions file_server.ts 100644 → 100755
@@ -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 { open, cwd } from "deno";
import { cwd, readFile, DenoError, ErrorKind } from "deno";

const addr = "0.0.0.0:4500";
const d = cwd();
const currentDir = cwd();

const encoder = new TextEncoder();

listenAndServe(addr, async req => {
const fileName = req.url.replace(/\/$/, '/index.html');
const filePath = currentDir + fileName;
let file;

listenAndServe(addr, async req => {
const filename = d + "/" + req.url;
let res;
try {
res = { status: 200, body: open(filename) };
file = await readFile(filePath);
} 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") });
}
return;
}

const headers = new Headers();
headers.set('content-type', 'octet-stream');

const res = {
status: 200,
body: file,
headers,
}
req.respond(res);
await req.respond(res);
});

console.log(`HTTP server listening on http://${addr}/`);
8 changes: 8 additions & 0 deletions http.ts
Expand Up @@ -82,6 +82,14 @@ export async function* serve(addr: string) {
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 {
status?: number;
headers?: Headers;
Expand Down

0 comments on commit c8e5d98

Please sign in to comment.