WebFund 2024F: Tutorial 2

From Soma-notes
Revision as of 04:38, 19 September 2024 by Soma (talk | contribs) (Created page with " ==Code== ===[https://homeostasis.scs.carleton.ca/~soma/webfund-2024f/code/simpleserver.js simpleserver.js]=== <syntaxhighlight lang="javascript" line> // 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 // functio...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Code

simpleserver.js

// 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);