Skip to content

Commit 2be75d0

Browse files
committed
Add libmagic to better process mime_types on Linux
Problem: serving files as application/application-octext-stream is annoying if the file is ASCII text Solution: When serving files on linux, libmagic can analyze the file to determine filetype when mime_guess has failed. Use libmagic to determine if a file is a plaintext file. Signed-off-by: Michael Mullin <[email protected]>
1 parent 2712a92 commit 2be75d0

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ htmlescape = "0.3.1"
3131
percent-encoding = "2.1.0"
3232
path-dedot = "1"
3333

34+
[target.'cfg(target_os="linux")'.dependencies]
35+
magic = "0.12.2"
36+
3437
[features]
3538
default = ["tls"]
3639
tls = ["hyper-native-tls"]

src/main.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -893,7 +893,24 @@ impl MainHandler {
893893
}
894894
Method::Get => {
895895
// Set mime type
896-
let mime = mime_types::from_path(path).first_or_octet_stream();
896+
//let mime = mime_types::from_path(path).first_or_octet_stream();
897+
let mime = if cfg!(target_os = "linux") {
898+
mime_types::from_path(path).first_or_else(|| {
899+
if let Ok(cookie) = magic::Cookie::open(magic::flags::MIME_TYPE) {
900+
if cookie.load::<&str>(&[]).is_ok() {
901+
if let Ok(val) = cookie.file(&path) {
902+
if val == "text/plain" {
903+
return mime_types::mime::TEXT_PLAIN;
904+
}
905+
}
906+
}
907+
}
908+
mime_types::mime::APPLICATION_OCTET_STREAM
909+
})
910+
} else {
911+
mime_types::from_path(path).first_or_octet_stream()
912+
};
913+
897914
resp.headers
898915
.set_raw("content-type", vec![mime.to_string().into_bytes()]);
899916

0 commit comments

Comments
 (0)