Add content-type header to file_server (denoland/deno_std#47)

Original: ab27371a01
This commit is contained in:
Bartek Iwańczuk 2018-12-31 10:06:06 +01:00 committed by Ryan Dahl
parent 95e378a28b
commit b65727734e
3 changed files with 93 additions and 0 deletions

View file

@ -12,6 +12,8 @@ import {
Response
} from "./http.ts";
import { cwd, DenoError, ErrorKind, args, stat, readDir, open } from "deno";
import { extname } from "../path/index.ts";
import * as extensionsMap from "./extension_map.json";
const dirViewerTemplate = `
<!DOCTYPE html>
@ -160,11 +162,30 @@ async function serveDir(req: ServerRequest, dirPath: string, dirName: string) {
return res;
}
function guessContentType(filename: string): string {
let extension = extname(filename);
let contentType = extensionsMap[extension];
if (contentType) {
return contentType;
}
extension = extension.toLowerCase();
contentType = extensionsMap[extension];
if (contentType) {
return contentType;
}
return extensionsMap[''];
}
async function serveFile(req: ServerRequest, filename: string) {
const file = await open(filename);
const fileInfo = await stat(filename);
const headers = new Headers();
headers.set("content-length", fileInfo.len.toString());
headers.set("content-type", guessContentType(filename));
const res = {
status: 200,