Media Types
Recipe | Crates | Categories |
---|---|---|
Get MIME type from string | ||
Get MIME type from filename | ||
Parse the MIME type of a HTTP response |
Get MIME type from string
The following example shows how to parse a mime::Mime
type from a string using the mime⮳ crate. mime::Mime
⮳ produces a default mime::Mime
⮳ type in an std::result::Result::unwrap_or
⮳ clause.
use mime::Mime; use mime::APPLICATION_OCTET_STREAM; fn main() { let invalid_mime_type = "i n v a l i d"; let default_mime = invalid_mime_type .parse::<Mime>() .unwrap_or(APPLICATION_OCTET_STREAM); println!( "MIME for {:?} used default value {:?}", invalid_mime_type, default_mime ); let valid_mime_type = "TEXT/PLAIN"; let parsed_mime = valid_mime_type .parse::<Mime>() .unwrap_or(APPLICATION_OCTET_STREAM); println!( "MIME for {:?} was parsed as {:?}", valid_mime_type, parsed_mime ); }
Get MIME type from filename
The following example shows how to return the correct MIME type from a given filename using the mime
⮳ crate. The program will check for file extensions and match against a known list. The return value is mime::Mime
⮳.
use mime::Mime; fn find_mimetype(filename: &str) -> Mime { let parts: Vec<&str> = filename.split('.').collect(); let res = match parts.last() { Some(v) => match *v { "png" => mime::IMAGE_PNG, "jpg" => mime::IMAGE_JPEG, "json" => mime::APPLICATION_JSON, &_ => mime::TEXT_PLAIN, }, None => mime::TEXT_PLAIN, }; res } fn main() { let filenames = vec!["foobar.jpg", "foo.bar", "foobar.png"]; for file in filenames { let mime = find_mimetype(file); println!("MIME for {}: {}", file, mime); } }
Parse the MIME type of a HTTP response
When receiving a HTTP response from reqwest
⮳ the MIME type
⮳ or media type may be found in the Content-Type
⮳ header. reqwest::header::HeaderMap::get
⮳ retrieves the header as a reqwest::header::HeaderValue
⮳ which can be converted to a string. The mime
⮳ crate can then parse that, yielding a mime::Mime
⮳ value.
The mime
⮳ crate also defines some commonly used MIME types.
Note that the reqwest::header
⮳ module is exported from the http
⮳ crate.
use std::str::FromStr; use anyhow::Result; use mime::Mime; use reqwest::header::CONTENT_TYPE; #[tokio::main] async fn main() -> Result<()> { let response = reqwest::get("https://www.rust-lang.org/logos/rust-logo-32x32.png") .await?; let headers = response.headers(); match headers.get(CONTENT_TYPE) { None => { println!("The response does not contain a Content-Type header."); } Some(content_type) => { let content_type = Mime::from_str(content_type.to_str()?)?; let media_type = match (content_type.type_(), content_type.subtype()) { (mime::TEXT, mime::HTML) => "a HTML document", (mime::TEXT, _) => "a text document", (mime::IMAGE, mime::PNG) => "a PNG image", (mime::IMAGE, _) => "an image", _ => "neither text nor image", }; println!("The reponse contains {}.", media_type); } }; Ok(()) }