Skip to content

Commit

Permalink
Add libmagic to better process mime_types on Linux
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
masmullin2000 committed Jan 23, 2022
1 parent 2712a92 commit 3acc35a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ htmlescape = "0.3.1"
percent-encoding = "2.1.0"
path-dedot = "1"

[target.'cfg(target_os="linux")'.dependencies]
magic = "*"

[features]
default = ["tls"]
tls = ["hyper-native-tls"]
19 changes: 18 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,24 @@ impl MainHandler {
}
Method::Get => {
// Set mime type
let mime = mime_types::from_path(path).first_or_octet_stream();
//let mime = mime_types::from_path(path).first_or_octet_stream();
let mime = if cfg!(target_os = "linux") {
mime_types::from_path(path).first_or_else(|| {
if let Ok(cookie) = magic::Cookie::open(magic::flags::MIME_TYPE) {
if cookie.load::<&str>(&[]).is_ok() {
if let Ok(val) = cookie.file(&path) {
if val == "text/plain" {
return mime_types::mime::TEXT_PLAIN;
}
}
}
}
mime_types::mime::APPLICATION_OCTET_STREAM
})
} else {
mime_types::from_path(path).first_or_octet_stream()
};

resp.headers
.set_raw("content-type", vec![mime.to_string().into_bytes()]);

Expand Down

0 comments on commit 3acc35a

Please sign in to comment.