Skip to main content

ssh_browser/origin/
mime.rs

1//! Extension to Content-Type.
2//!
3//! Short on purpose, but two entries are load-bearing rather than cosmetic. A
4//! browser refuses to execute an ES module served as `application/octet-stream`,
5//! so getting `.mjs` and `.js` wrong makes a working page look broken in a way
6//! that has nothing to do with the transport.
7
8pub fn guess(path: &str) -> &'static str {
9    let name = path.rsplit('/').next().unwrap_or(path);
10    let Some((_, ext)) = name.rsplit_once('.') else {
11        return "application/octet-stream";
12    };
13    match ext.to_ascii_lowercase().as_str() {
14        "html" | "htm" => "text/html; charset=utf-8",
15        "css" => "text/css; charset=utf-8",
16        "js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
17        "json" | "map" => "application/json",
18        "wasm" => "application/wasm",
19        "svg" => "image/svg+xml",
20        "png" => "image/png",
21        "jpg" | "jpeg" => "image/jpeg",
22        "gif" => "image/gif",
23        "webp" => "image/webp",
24        "avif" => "image/avif",
25        "ico" => "image/x-icon",
26        "woff" => "font/woff",
27        "woff2" => "font/woff2",
28        "ttf" => "font/ttf",
29        "otf" => "font/otf",
30        "pdf" => "application/pdf",
31        "txt" | "log" => "text/plain; charset=utf-8",
32        "md" => "text/markdown; charset=utf-8",
33        "xml" => "application/xml",
34        "csv" => "text/csv; charset=utf-8",
35        "mp4" => "video/mp4",
36        "webm" => "video/webm",
37        "mp3" => "audio/mpeg",
38        "wav" => "audio/wav",
39        _ => "application/octet-stream",
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn modules_get_a_type_a_browser_will_execute() {
49        assert_eq!(guess("/a/b.mjs"), "text/javascript; charset=utf-8");
50        assert_eq!(guess("/a/b.js"), "text/javascript; charset=utf-8");
51    }
52
53    #[test]
54    fn the_extension_comes_from_the_basename_not_the_path() {
55        // A dot in a directory name must not be read as the file's extension.
56        assert_eq!(guess("/a.css/b"), "application/octet-stream");
57        assert_eq!(guess("/a.css/b.html"), "text/html; charset=utf-8");
58    }
59
60    #[test]
61    fn unknown_and_extensionless_fall_back() {
62        assert_eq!(guess("/README"), "application/octet-stream");
63        assert_eq!(guess("/a.qqq"), "application/octet-stream");
64    }
65}