brows3_lib/s3/
content_type.rs1use crate::error::{AppError, Result};
2
3pub fn infer_content_type(key: &str) -> String {
4 mime_guess::from_path(key)
5 .first_or_octet_stream()
6 .essence_str()
7 .to_string()
8}
9
10pub fn validate_content_type(value: &str) -> Result<String> {
11 let value = value.trim();
12 if value.is_empty() {
13 return Err(AppError::ConfigError(
14 "Content-Type cannot be empty".to_string(),
15 ));
16 }
17 if value.len() > 255 {
18 return Err(AppError::ConfigError(
19 "Content-Type cannot exceed 255 characters".to_string(),
20 ));
21 }
22
23 let parsed = value.parse::<mime::Mime>().map_err(|_| {
24 AppError::ConfigError(format!(
25 "Invalid Content-Type '{}'. Use a media type such as text/html or application/json.",
26 value
27 ))
28 })?;
29
30 if parsed.type_() == mime::STAR || parsed.subtype() == mime::STAR {
31 return Err(AppError::ConfigError(
32 "Content-Type cannot contain a wildcard".to_string(),
33 ));
34 }
35
36 Ok(parsed.to_string())
37}
38
39#[cfg(test)]
40mod tests {
41 use super::{infer_content_type, validate_content_type};
42
43 #[test]
44 fn common_web_files_get_browser_compatible_content_types() {
45 assert_eq!(infer_content_type("site/index.html"), "text/html");
46 assert_eq!(infer_content_type("assets/styles.css"), "text/css");
47 assert_eq!(infer_content_type("data/report.json"), "application/json");
48 assert_eq!(
49 infer_content_type("unknown.custom-extension"),
50 "application/octet-stream"
51 );
52 }
53
54 #[test]
55 fn custom_content_types_are_parsed_and_validated() {
56 assert_eq!(
57 validate_content_type(" text/html; charset=utf-8 ").unwrap(),
58 "text/html; charset=utf-8"
59 );
60 assert!(validate_content_type("not a media type").is_err());
61 assert!(validate_content_type("text/*").is_err());
62 assert!(validate_content_type("").is_err());
63 }
64}