diff --git a/gleam.toml b/gleam.toml index 3b1b7f5..c694cc8 100644 --- a/gleam.toml +++ b/gleam.toml @@ -12,6 +12,7 @@ gleam_stdlib = ">= 0.34.0 and < 2.0.0" snag = ">= 0.3.0 and < 1.0.0" gleam_http = ">= 3.6.0 and < 4.0.0" gleam_json = ">= 1.0.0 and < 3.0.0" +filepath = ">= 1.0.0 and < 2.0.0" [dev-dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" diff --git a/manifest.toml b/manifest.toml index 7522515..af1fb43 100644 --- a/manifest.toml +++ b/manifest.toml @@ -2,6 +2,7 @@ # You typically do not need to edit this file packages = [ + { name = "filepath", version = "1.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "filepath", source = "hex", outer_checksum = "EFB6FF65C98B2A16378ABC3EE2B14124168C0CE5201553DE652E2644DCFDB594" }, { name = "gleam_http", version = "3.7.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_http", source = "hex", outer_checksum = "EA66440C2269F7CED0F6845E5BD0DB68095775D627FA709A841CA78A398D6D56" }, { name = "gleam_json", version = "2.0.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_json", source = "hex", outer_checksum = "CB10B0E7BF44282FB25162F1A24C1A025F6B93E777CCF238C4017E4EEF2CDE97" }, { name = "gleam_stdlib", version = "0.40.0", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "86606B75A600BBD05E539EB59FABC6E307EEEA7B1E5865AFB6D980A93BCB2181" }, @@ -10,6 +11,7 @@ packages = [ ] [requirements] +filepath = { version = ">= 1.0.0 and < 2.0.0" } gleam_http = { version = ">= 3.6.0 and < 4.0.0" } gleam_json = { version = ">= 1.0.0 and < 3.0.0" } gleam_stdlib = { version = ">= 0.34.0 and < 2.0.0" } diff --git a/src/midas/task.gleam b/src/midas/task.gleam index c80d8e0..f4a96a4 100644 --- a/src/midas/task.gleam +++ b/src/midas/task.gleam @@ -1,3 +1,4 @@ +import filepath import gleam/http/request.{type Request} import gleam/http/response.{type Response} import gleam/list @@ -175,6 +176,28 @@ pub fn serve(port, handle) { Serve(port, handle, result_to_effect(_, serve_error_reason)) } +pub fn serve_static(port, files) { + let handle = fn(request) { + let request.Request(path: path, ..) = request + let mime = case filepath.extension(path) { + Ok(".js") -> "application/javascript" + Ok(_) -> "application/octet-stream" + // index pages are assumed to be html + Error(Nil) -> "text/html" + } + case list.key_find(files, path) { + Ok(content) -> + response.new(200) + |> response.set_header("content-type", mime) + |> response.set_body(content) + Error(Nil) -> + response.new(404) + |> response.set_body(<<>>) + } + } + serve(port, handle) +} + fn serve_error_reason(message) { snag.new("Failed to start server: " <> message) }