packages
The Louise packages, each released on its own
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#28 · main · 3 min 34 s
0Étoiles
0Forks
3Issues
| 1 | /// Static files: a request's path segments answered from a directory, with |
| 2 | /// a content type from the file's extension and a cache rule of the |
| 3 | /// caller's. |
| 4 | |
| 5 | import std/file |
| 6 | import std/http.{type Response} |
| 7 | import std/list |
| 8 | import std/option |
| 9 | import std/string |
| 10 | |
| 11 | /// The file at `segments` under `root`, with the `Cache-Control` that |
| 12 | /// `caching` gives its segments. Not found when the file is missing, and |
| 13 | /// for any segment that is hidden (`.` first) or holds a separator, so a |
| 14 | /// path never leaves `root`. |
| 15 | pub fn serve :: |
| 16 | root: String |
| 17 | caching: fn(List<String>) -> String |
| 18 | segments: List<String> |
| 19 | -> Response / <io> |
| 20 | { |
| 21 | if segments == [] || list.any segments hidden |
| 22 | { |
| 23 | http.not_found () |
| 24 | } |
| 25 | else |
| 26 | { |
| 27 | let path = string.join [root, ..segments] "/" |
| 28 | match file.read_bytes path |
| 29 | { Ok(content) -> |
| 30 | http.response 200 (content_type path) content |
| 31 | |> http.with_header "Cache-Control" (caching segments) |
| 32 | , Error(_) -> http.not_found () |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn hidden :: segment: String -> Bool |
| 38 | { |
| 39 | string.starts_with segment "." || string.contains segment "/" |
| 40 | || string.contains segment "\\" |
| 41 | } |
| 42 | |
| 43 | fn content_type :: path: String -> String |
| 44 | { |
| 45 | let types = |
| 46 | [ (".css", "text/css; charset=utf-8") |
| 47 | , (".js", "text/javascript; charset=utf-8") |
| 48 | , (".svg", "image/svg+xml") |
| 49 | , (".png", "image/png") |
| 50 | , (".webp", "image/webp") |
| 51 | , (".jpg", "image/jpeg") |
| 52 | , (".jpeg", "image/jpeg") |
| 53 | , (".avif", "image/avif") |
| 54 | , (".gif", "image/gif") |
| 55 | , (".webmanifest", "application/manifest+json") |
| 56 | , (".json", "application/json") |
| 57 | , (".woff2", "font/woff2") |
| 58 | , (".ico", "image/x-icon") |
| 59 | , (".txt", "text/plain; charset=utf-8") |
| 60 | ] |
| 61 | list.find types fn t { string.ends_with path t.0 } |
| 62 | |> option.map fn t { t.1 } |
| 63 | |> option.unwrap_or "application/octet-stream" |
| 64 | } |