/// Static files: a request's path segments answered from a directory, with /// a content type from the file's extension and a cache rule of the /// caller's. import std/file import std/http.{type Response} import std/list import std/option import std/string /// The file at `segments` under `root`, with the `Cache-Control` that /// `caching` gives its segments. Not found when the file is missing, and /// for any segment that is hidden (`.` first) or holds a separator, so a /// path never leaves `root`. pub fn serve :: root: String caching: fn(List) -> String segments: List -> Response / { if segments == [] || list.any segments hidden { http.not_found () } else { let path = string.join [root, ..segments] "/" match file.read_bytes path { Ok(content) -> http.response 200 (content_type path) content |> http.with_header "Cache-Control" (caching segments) , Error(_) -> http.not_found () } } } fn hidden :: segment: String -> Bool { string.starts_with segment "." || string.contains segment "/" || string.contains segment "\\" } fn content_type :: path: String -> String { let types = [ (".css", "text/css; charset=utf-8") , (".js", "text/javascript; charset=utf-8") , (".svg", "image/svg+xml") , (".png", "image/png") , (".webp", "image/webp") , (".jpg", "image/jpeg") , (".jpeg", "image/jpeg") , (".avif", "image/avif") , (".gif", "image/gif") , (".webmanifest", "application/manifest+json") , (".json", "application/json") , (".woff2", "font/woff2") , (".ico", "image/x-icon") , (".txt", "text/plain; charset=utf-8") ] list.find types fn t { string.ends_with path t.0 } |> option.map fn t { t.1 } |> option.unwrap_or "application/octet-stream" }