#header #http-header #http #content-negotiation

accept-header

A simple library for parsing HTTP Accept headers for content negotiation

4 releases

0.2.3 Feb 14, 2023
0.2.2 Jan 11, 2023
0.2.1 Nov 27, 2022
0.1.2 Nov 14, 2022

#89 in #http-header

Download history 144/week @ 2024-11-16 306/week @ 2024-11-23 375/week @ 2024-11-30 498/week @ 2024-12-07 453/week @ 2024-12-14 218/week @ 2024-12-21 165/week @ 2024-12-28 279/week @ 2025-01-04 251/week @ 2025-01-11 233/week @ 2025-01-18 253/week @ 2025-01-25 541/week @ 2025-02-01 2363/week @ 2025-02-08 2455/week @ 2025-02-15 1076/week @ 2025-02-22 4606/week @ 2025-03-01

10,596 downloads per month
Used in 2 crates

MIT license

14KB
309 lines

HTTP accept header

A very basic & naive implementation of the HTTP Accept header. It uses http crate and mime crate to parse the accept header. Basic data structure:

#[derive(Debug, Clone, PartialEq)]
pub struct Accept {
    pub wildcard: Option<MediaType>,
    pub types: Vec<MediaType>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct MediaType {
    pub mime: Mime,
    pub weight: Option<f32>,
}

Usage:

// parse accept header
let accept: Accept = "application/json, text/html;q=0.9, text/plain;q=0.8, */*;q=0.7"
    .parse()
    .unwrap();

// prepare a list of supported media types
let available = vec![
    Mime::from_str("text/html").unwrap(),
    Mime::from_str("application/json").unwrap(),
];

// content negotiation
let negotiated = accept.negotiate(&available).unwrap();

// "application/json" shall be chosen since it is available and has the highest weight
assert_eq!(negotiated, Mime::from_str("application/json").unwrap());

Dependencies

~3MB
~60K SLoC