Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions static-serve-macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ proc-macro = true
display_full_error = "1.1"
flate2 = "1.1"
glob = "0.3"
mime_guess = "2.0.5"
proc-macro2 = "1.0"
quote = "1.0"
sha1 = "0.10"
Expand Down
2 changes: 2 additions & 0 deletions static-serve-macro/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use thiserror::Error;
pub(crate) enum Error {
#[error("{}", UnknownFileExtension(.0.as_deref()))]
UnknownFileExtension(Option<OsString>),
#[error("File extension for file {} is not valid unicode", 0.to_string())]
InvalidFileExtension(OsString),
#[error("Cannot canonicalize assets directory")]
CannotCanonicalizeDirectory(#[source] io::Error),
#[error("Invalid unicode in directory name")]
Expand Down
29 changes: 21 additions & 8 deletions static-serve-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,15 +357,28 @@ fn maybe_get_compressed(compressed: &[u8], contents: &[u8]) -> Option<LitByteStr
.then(|| LitByteStr::new(compressed, Span::call_site()))
}

fn file_content_type(path: &Path) -> Result<&'static str, error::Error> {
/// Use `mime_guess` to get the best guess of the file's MIME type
/// by looking at its extension, or return an error if unable.
///
/// We accept the first guess because [`mime_guess` updates the order
/// according to the latest IETF RTC](https://docs.rs/mime_guess/2.0.5/mime_guess/struct.MimeGuess.html#note-ordering)
fn file_content_type(path: &Path) -> Result<String, error::Error> {
match path.extension() {
Some(ext) if ext.eq_ignore_ascii_case("css") => Ok("text/css"),
Some(ext) if ext.eq_ignore_ascii_case("js") => Ok("text/javascript"),
Some(ext) if ext.eq_ignore_ascii_case("txt") => Ok("text/plain"),
Some(ext) if ext.eq_ignore_ascii_case("woff") => Ok("font/woff"),
Some(ext) if ext.eq_ignore_ascii_case("woff2") => Ok("font/woff2"),
Some(ext) if ext.eq_ignore_ascii_case("svg") => Ok("image/svg+xml"),
ext => Err(error::Error::UnknownFileExtension(ext.map(Into::into))),
Some(ext) => {
let guesses = mime_guess::MimeGuess::from_ext(
ext.to_str()
.ok_or(error::Error::InvalidFileExtension(path.into()))?,
);

if let Some(guess) = guesses.first_raw() {
Ok(guess.to_owned())
} else {
Err(error::Error::UnknownFileExtension(
path.extension().map(Into::into),
))
}
}
None => Err(error::Error::UnknownFileExtension(None)),
}
}

Expand Down