Skip to main content

compmd_host/
content_type.rs

1//! A served file's type, by its extension: what a bundle's files are.
2
3use std::path::Path;
4
5/// The type of the file at `path`, by its extension; `application/octet-stream` for any other.
6#[must_use]
7pub fn content_type(path: &str) -> &'static str {
8    match Path::new(path)
9        .extension()
10        .and_then(|extension| extension.to_str())
11    {
12        Some("html") => "text/html; charset=utf-8",
13        Some("js" | "mjs") => "text/javascript; charset=utf-8",
14        Some("css") => "text/css; charset=utf-8",
15        Some("json" | "map") => "application/json",
16        Some("wasm") => "application/wasm",
17        Some("svg") => "image/svg+xml",
18        Some("png") => "image/png",
19        Some("woff2") => "font/woff2",
20        Some("woff") => "font/woff",
21        Some("ttf") => "font/ttf",
22        _ => "application/octet-stream",
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn each_kind_of_file_has_its_type() {
32        for (name, kind) in [
33            ("a.html", "text/html; charset=utf-8"),
34            ("a.js", "text/javascript; charset=utf-8"),
35            ("a.mjs", "text/javascript; charset=utf-8"),
36            ("a.css", "text/css; charset=utf-8"),
37            ("a.json", "application/json"),
38            ("a.js.map", "application/json"),
39            ("a.wasm", "application/wasm"),
40            ("a.svg", "image/svg+xml"),
41            ("a.png", "image/png"),
42            ("a.woff2", "font/woff2"),
43            ("a.woff", "font/woff"),
44            ("a.ttf", "font/ttf"),
45            ("a", "application/octet-stream"),
46        ] {
47            assert_eq!(content_type(name), kind, "{name}");
48        }
49    }
50}