glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Request formats and their media types, as Rails' `Mime` registry knows
//! them: `/posts/1.json` or `Accept: application/json` asks for JSON.

/// Rails' registered types: (format, media type, extensions, synonyms).
const TYPES: &[(&str, &str, &[&str], &[&str])] = &[
    ("html", "text/html", &["xhtml"], &["application/xhtml+xml"]),
    ("text", "text/plain", &["txt"], &[]),
    (
        "js",
        "text/javascript",
        &["mjs"],
        &["application/javascript", "application/x-javascript"],
    ),
    ("css", "text/css", &[], &[]),
    ("ics", "text/calendar", &[], &[]),
    ("csv", "text/csv", &[], &[]),
    ("vcf", "text/vcard", &[], &[]),
    ("vtt", "text/vtt", &[], &[]),
    ("png", "image/png", &[], &[]),
    (
        "jpeg",
        "image/jpeg",
        &["jpg", "jpe", "pjpeg"],
        &["image/pjpeg"],
    ),
    ("gif", "image/gif", &[], &[]),
    ("bmp", "image/bmp", &[], &[]),
    ("tiff", "image/tiff", &["tif"], &[]),
    ("svg", "image/svg+xml", &[], &[]),
    ("mpeg", "video/mpeg", &["mpg", "mpe"], &[]),
    ("mp3", "audio/mpeg", &["mp1", "mp2"], &[]),
    ("ogg", "audio/ogg", &["oga", "spx", "opus"], &[]),
    ("m4a", "audio/aac", &["mpg4", "aac"], &["audio/mp4"]),
    ("webm", "video/webm", &[], &[]),
    ("mp4", "video/mp4", &["m4v"], &[]),
    ("otf", "font/otf", &[], &[]),
    ("ttf", "font/ttf", &[], &[]),
    ("woff", "font/woff", &[], &[]),
    ("woff2", "font/woff2", &[], &[]),
    (
        "xml",
        "application/xml",
        &[],
        &["text/xml", "application/x-xml"],
    ),
    ("rss", "application/rss+xml", &[], &[]),
    ("atom", "application/atom+xml", &[], &[]),
    ("yaml", "application/x-yaml", &["yml"], &["text/yaml"]),
    ("multipart_form", "multipart/form-data", &[], &[]),
    (
        "url_encoded_form",
        "application/x-www-form-urlencoded",
        &[],
        &[],
    ),
    (
        "json",
        "application/json",
        &[],
        &["text/x-json", "application/jsonrequest"],
    ),
    ("pdf", "application/pdf", &[], &[]),
    ("zip", "application/zip", &[], &[]),
    ("gzip", "application/gzip", &["gz"], &["application/x-gzip"]),
];

/// The media type for a format or file extension: `json` →
/// `application/json`, `jpg` → `image/jpeg`.
pub fn for_format(format: &str) -> Option<&'static str> {
    TYPES
        .iter()
        .find(|(name, _, extensions, _)| *name == format || extensions.contains(&format))
        .map(|(_, media_type, _, _)| *media_type)
}

/// The registered media type a client's type names: `text/xml` →
/// `application/xml`. Unregistered types and wildcards have none.
pub fn canonical(media_type: &str) -> Option<&'static str> {
    TYPES
        .iter()
        .find(|(_, media, _, synonyms)| *media == media_type || synonyms.contains(&media_type))
        .map(|(_, media_type, _, _)| *media_type)
}

/// The media type a request asks for, as Rails picks it: the `format`
/// (from `/posts/1.json`) if there is one, else the `Accept` header's
/// preferred type unless it reads like a browser's (`…, */*`). `None` when
/// that type isn't a registered one, or nothing was asked for.
pub fn requested(format: Option<&str>, accept: Option<&str>) -> Option<&'static str> {
    if let Some(format) = format {
        return for_format(format);
    }
    let accept = accept?.trim();
    if accept.is_empty() || browser_like(accept) {
        return None;
    }
    canonical(&preferred(accept))
}

/// Rails' `BROWSER_LIKE_ACCEPTS`: a wildcard alongside other types.
fn browser_like(accept: &str) -> bool {
    accept.split(',').count() > 1 && accept.split(',').any(|part| part.trim().starts_with("*/*"))
}

/// The first type with the highest quality.
fn preferred(accept: &str) -> String {
    let mut best: Option<(f32, &str)> = None;
    for part in accept.split(',') {
        let mut pieces = part.split(';');
        let media_type = pieces.next().unwrap_or("").trim();
        let quality = pieces
            .filter_map(|p| p.trim().strip_prefix("q="))
            .find_map(|q| q.trim().parse::<f32>().ok())
            .unwrap_or(1.0);
        if best.is_none_or(|(q, _)| quality > q) {
            best = Some((quality, media_type));
        }
    }
    best.map(|(_, t)| t.to_ascii_lowercase())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Each case as the Rails app answered `head` (`text/html` is its
    /// fallback when this returns `None`).
    #[test]
    fn picks_types_as_rails_does() {
        let cases: &[(Option<&str>, Option<&str>, Option<&str>)] = &[
            (None, None, None),
            (None, Some("*/*"), None),
            (None, Some("application/json"), Some("application/json")),
            (None, Some("text/csv"), Some("text/csv")),
            (None, Some("application/x-foo"), None),
            (None, Some("image/*"), None),
            (
                None,
                Some("application/json, text/plain"),
                Some("application/json"),
            ),
            (
                None,
                Some("application/json; charset=utf-8"),
                Some("application/json"),
            ),
            (
                None,
                Some("text/plain;q=0.5, application/json"),
                Some("application/json"),
            ),
            (None, Some("text/x-json"), Some("application/json")),
            (None, Some("text/xml"), Some("application/xml")),
            (
                None,
                Some("text/html,application/xhtml+xml,*/*;q=0.8"),
                None,
            ),
            (None, Some("application/json, */*"), None),
            (Some("json"), Some("text/html"), Some("application/json")),
            (Some("xml"), None, Some("application/xml")),
            (Some("csv"), Some("application/json"), Some("text/csv")),
            (Some("jpg"), None, Some("image/jpeg")),
            (Some("yml"), None, Some("application/x-yaml")),
            (Some("txt"), None, Some("text/plain")),
            (Some("foo"), Some("application/json"), None),
        ];
        for (format, accept, expected) in cases {
            assert_eq!(
                requested(*format, *accept),
                *expected,
                "{format:?} {accept:?}"
            );
        }
    }
}