How do I add content-type to HTTP.jl server?

Main problem here is, when serving *.js file:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

How do I add content-type to the HTTP.jl server ?

Existing code:

using HTTP

const HOST = ""
const PORT = 8080

println("Server Started")

router_8080 = HTTP.Router();
router_8001 = HTTP.Router();

const www_root = "/voxel/www/"

function do_8080(r::HTTP.Request) == "/" && return HTTP.Response(200, read(www_root * "index.html"))
    local path = www_root * sanitize_path(;
    return isfile(path) ? HTTP.Response(200, read(path)) : HTTP.Response(404)

function sanitize_path(s :: String)
    local t = split(s, "/");
    local t = filter(s -> s != "." && s != "..", t)
    return join(t, "/")

function do_8001(::HTTP.Request)
    return HTTP.Response(200, "Hello World 8001")

HTTP.register!(router_8080, "GET", "/", do_8080)
HTTP.register!(router_8080, "GET", "*", do_8080)

HTTP.register!(router_8001, "GET", "/", do_8001)
HTTP.register!(router_8001, "GET", "*", do_8001)

@async HTTP.serve(router_8080, "", 8080)
HTTP.serve(router_8001, "", 8001)

Side note: if this is going to be publicly facing you’d probably be better off with a battle-tested file server that has more robust path sanitizing, support of range requests, etc. E.g. you could run nginx, have it serve static files, then reverse proxy anything to julia that needs to be.

That said, Content-Type is just passed as a header.

    ["Content-Type" => "application/javascript"], 

HTTP.jl doesn’t have anything built-in to map file extensions to mimetypes, but e.g. you could start with a list like this one from python mapping commonly used extensions.

1 Like