Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attach correct Content-Type to HTTP header #4555

Merged
merged 6 commits into from
Apr 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 45 additions & 37 deletions std/http/file_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
// https://github.com/indexzero/http-server/blob/master/test/http-server-test.js

const { args, stat, readdir, open, exit } = Deno;
import { posix } from "../path/mod.ts";
import { contentType } from "../media_types/mod.ts";
import { posix, extname } from "../path/mod.ts";
import { listenAndServe, ServerRequest, Response } from "./server.ts";
import { parse } from "../flags/mod.ts";
import { assert } from "../testing/asserts.ts";
Expand Down Expand Up @@ -96,21 +97,22 @@ function fileLenToString(len: number): string {
return `${(len / base).toFixed(2)}${suffix[suffixIndex]}`;
}

async function serveFile(
export async function serveFile(
req: ServerRequest,
filePath: string
): Promise<Response> {
const [file, fileInfo] = await Promise.all([open(filePath), stat(filePath)]);
const headers = new Headers();
headers.set("content-length", fileInfo.size.toString());
headers.set("content-type", "text/plain; charset=utf-8");
ry marked this conversation as resolved.
Show resolved Hide resolved

const res = {
const contentTypeValue = contentType(extname(filePath));
if (contentTypeValue) {
headers.set("content-type", contentTypeValue);
}
return {
status: 200,
body: file,
headers,
};
return res;
}

// TODO: simplify this after deno.stat and deno.readdir are fixed
Expand Down Expand Up @@ -296,39 +298,45 @@ function html(strings: TemplateStringsArray, ...values: unknown[]): string {
return html;
}

listenAndServe(
addr,
async (req): Promise<void> => {
let normalizedUrl = posix.normalize(req.url);
try {
normalizedUrl = decodeURIComponent(normalizedUrl);
} catch (e) {
if (!(e instanceof URIError)) {
throw e;
function main(): void {
listenAndServe(
addr,
async (req): Promise<void> => {
let normalizedUrl = posix.normalize(req.url);
try {
normalizedUrl = decodeURIComponent(normalizedUrl);
} catch (e) {
if (!(e instanceof URIError)) {
throw e;
}
}
}
const fsPath = posix.join(target, normalizedUrl);
const fsPath = posix.join(target, normalizedUrl);

let response: Response | undefined;
try {
const info = await stat(fsPath);
if (info.isDirectory()) {
response = await serveDir(req, fsPath);
} else {
response = await serveFile(req, fsPath);
let response: Response | undefined;
try {
const info = await stat(fsPath);
if (info.isDirectory()) {
response = await serveDir(req, fsPath);
} else {
response = await serveFile(req, fsPath);
}
} catch (e) {
console.error(e.message);
response = await serveFallback(req, e);
} finally {
if (CORSEnabled) {
assert(response);
setCORS(response);
}
serverLog(req, response!);
req.respond(response!);
}
} catch (e) {
console.error(e.message);
response = await serveFallback(req, e);
} finally {
if (CORSEnabled) {
assert(response);
setCORS(response);
}
serverLog(req, response!);
req.respond(response!);
}
}
);
);

console.log(`HTTP server listening on https://${addr}/`);
console.log(`HTTP server listening on https://${addr}/`);
}

if (import.meta.main) {
main();
}
12 changes: 11 additions & 1 deletion std/http/file_server_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import { assert, assertEquals, assertStrContains } from "../testing/asserts.ts";
import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts";
import { ServerRequest } from "./server.ts";
import { serveFile } from "./file_server.ts";
const { test } = Deno;
let fileServer: Deno.Process;

Expand Down Expand Up @@ -31,7 +33,7 @@ function killFileServer(): void {
fileServer.stdout?.close();
}

test(async function serveFile(): Promise<void> {
test("file_server serveFile", async (): Promise<void> => {
await startFileServer();
try {
const res = await fetch("https://localhost:4500/README.md");
Expand Down Expand Up @@ -141,3 +143,11 @@ test(async function printHelp(): Promise<void> {
helpProcess.close();
helpProcess.stdout.close();
});

test("contentType", async () => {
const request = new ServerRequest();
const response = await serveFile(request, "http/testdata/hello.html");
const contentType = response.headers!.get("content-type");
assertEquals(contentType, "text/html; charset=utf-8");
(response.body as Deno.File).close();
});
Empty file added std/http/testdata/hello.html
Empty file.