hornwitser.no/utils/http-server.ts

83 lines
1.8 KiB
TypeScript
Raw Normal View History

import * as http from "node:http";
import * as posix from "node:path/posix";
function writeResponse(
response: http.ServerResponse,
statusCode: number,
statusMessage: string,
mimeType: string | undefined,
content: Buffer,
suppressContent = false,
) {
response.statusCode = statusCode;
response.statusMessage = statusMessage;
if (mimeType !== undefined) {
response.setHeader("Content-Type", mimeType);
}
response.setHeader("Content-Length", content.length);
if (!suppressContent) {
response.end(content);
} else {
response.end();
}
};
function writeNotFound(response: http.ServerResponse, suppressContent = false) {
writeResponse(
response,
404, "Not Found",
"text/plain",
Buffer.from("404 Not Found"),
suppressContent,
);
}
function writeBadRequest(response: http.ServerResponse, suppressContent = false) {
writeResponse(
response,
400, "Bad Request",
"text/plain",
Buffer.from("400 Bad Request"),
suppressContent,
);
}
const extToMimeType = new Map([
[".js", "text/javascript"],
[".html", "text/html"],
[".css", "text/css"],
]);
export function createServer(
get: (ref: string) => Buffer | undefined
) {
const server = http.createServer(
{
joinDuplicateHeaders: true,
// @ts-expect-error missing in type declaration
rejectNonStandardBodyWrites: true,
},
(request, response) => {
const url = new URL(`http://localhost${request.url}`);
if (request.method === "GET" || request.method === "HEAD") {
const content = get(url.pathname);
const isHead = request.method === "HEAD";
if (!content) {
writeNotFound(response, isHead);
return;
}
writeResponse(
response,
200, "OK",
extToMimeType.get(posix.extname(url.pathname)),
content,
isHead,
)
return;
}
writeBadRequest(response);
},
);
return server;
}