Crate headers_accept

source ·
Expand description

Provides a struct Accept which implements Header and owns a list of MediaTypeBuf in precedence order.

See RFC 9110, 12.5.1 Accept.

§Examples

use std::str::FromStr;

use headers_accept::Accept;
use mediatype::MediaTypeBuf;

let accept = Accept::from_str("audio/*; q=0.2, audio/basic").unwrap();
let mut media_types = accept.media_types();
assert_eq!(
    media_types.next(),
    Some(&MediaTypeBuf::from_str("audio/basic").unwrap())
);
assert_eq!(
    media_types.next(),
    Some(&MediaTypeBuf::from_str("audio/*; q=0.2").unwrap())
);
assert_eq!(media_types.next(), None);

Content type negotiation is also facilitated through a method, negotiate, which allows a user agent and server to determine the best shared format.

const TEXT_HTML: MediaType = MediaType::new(TEXT, HTML);
const APPLICATION_JSON: MediaType = MediaType::new(APPLICATION, JSON);

const AVAILABLE: &[MediaType] = &[TEXT_HTML, APPLICATION_JSON];

let accept = Accept::from_str(
    "text/html, application/xhtml+xml, application/xml;q=0.9, text/*;q=0.7, text/csv;q=0",
)
.unwrap();

assert_eq!(accept.negotiate(AVAILABLE), Some(&TEXT_HTML));

Structs§

  • Represents a parsed Accept HTTP header.