Media Types

Get a MIME type from a string

mime cat-encoding cat-web-programming

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::APPLICATION_OCTET_STREAM;
use mime::Mime;

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 a MIME type from a filename

mime cat-encoding cat-web-programming

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

reqwest mime cat-network-programming cat-encoding cat-web-programming

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(())
}