Expand description
§negotiator — HTTP content negotiation
Choose the response representation a client prefers, from the Accept,
Accept-Charset, Accept-Encoding, and Accept-Language request headers. This is a
faithful Rust port of the widely-used negotiator
npm package (the engine behind Express’s req.accepts*), which has no Rust equivalent.
Each negotiation answers two questions:
- Given the server’s available options, which does the client prefer (and in what order)?
- Or, with no list provided, what does the client accept, sorted by preference?
Zero dependencies and #![no_std] (needs only alloc).
use negotiator::Negotiator;
let n = Negotiator::new()
.accept("text/html, application/json;q=0.9, */*;q=0.1")
.accept_language("en-US, fr;q=0.8")
.accept_encoding("gzip, br;q=0.9");
assert_eq!(n.media_type(Some(&["application/json", "text/html"])).as_deref(), Some("text/html"));
assert_eq!(n.language(Some(&["fr", "en"])).as_deref(), Some("en"));
assert_eq!(n.encoding(Some(&["gzip", "br"]), None).as_deref(), Some("gzip"));The free functions preferred_media_types, preferred_charsets,
preferred_encodings, and preferred_languages expose the same logic directly.
In all of them, a header of None means “absent” (which RFC 7231 treats as accept
everything), while Some("") means an explicit empty header (accept nothing).
Structs§
- Negotiator
- A content negotiator over a request’s
Accept*headers.
Functions§
- preferred_
charsets - Return the acceptable charsets from an
Accept-Charsetheader, most-preferred first. - preferred_
encodings - Return the acceptable encodings from an
Accept-Encodingheader, most-preferred first. - preferred_
languages - Return the acceptable languages from an
Accept-Languageheader, most-preferred first. - preferred_
media_ types - Return the acceptable media types from an
Acceptheader, most-preferred first.