// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2024 Anil Somayaji
//
// simpleserver.js
// for COMP 2406 (Fall 2024), Carleton University
//
// Initial version: Sept 18, 2024
//
// Originally inspired by Rod Waldhoff's tiny node.js webserver
// https://github.com/rodw/tiny-node.js-webserver
//
function MIMEtype(filename) {
const MIME_TYPES = {
'css': 'text/css',
'gif': 'image/gif',
'htm': 'text/html',
'html': 'text/html',
'ico': 'image/x-icon',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'js': 'text/javascript',
'json': 'application/json',
'png': 'image/png',
'txt': 'text/text'
};
var extension = "";
if (filename) {
extension = filename.slice(filename.lastIndexOf('.')+1).toLowerCase();
}
return MIME_TYPES[extension] || "application/octet-stream";
};
async function handler(req) {
var metadata = {
status: 200,
contentType: "text/plain"
}
const pathname = "." + new URL(req.url).pathname;
var contents;
metadata.contentType = MIMEtype(pathname);
try {
contents = await Deno.readFile(pathname);
} catch (e) {
contents = null;
}
if (!contents) {
contents = "File not found: " + pathname;
metadata.contentType = "text/plain";
metadata.status = 404;
console.log("error on request for " + pathname);
} else {
console.log("returning " + pathname +
" of type " + metadata.contentType);
}
return new Response(contents, metadata);
}
Deno.serve(handler);