16 releases

Uses old Rust 2015

0.4.0 Nov 24, 2023
0.3.8 Sep 2, 2022
0.3.7 Feb 10, 2022
0.3.5 Oct 18, 2021
0.1.0 Aug 9, 2016

#11 in Web programming

Download history 414024/week @ 2024-07-21 412834/week @ 2024-07-28 449798/week @ 2024-08-04 536056/week @ 2024-08-11 564198/week @ 2024-08-18 568892/week @ 2024-08-25 520582/week @ 2024-09-01 590163/week @ 2024-09-08 509344/week @ 2024-09-15 590381/week @ 2024-09-22 587631/week @ 2024-09-29 653180/week @ 2024-10-06 622189/week @ 2024-10-13 682787/week @ 2024-10-20 673045/week @ 2024-10-27 660963/week @ 2024-11-03

2,663,645 downloads per month
Used in 1,422 crates (171 directly)

MIT license

315KB
6K SLoC

rust http headers

Build Status

Typed HTTP headers.


lib.rs:

Typed HTTP Headers

hyper has the opinion that headers should be strongly-typed, because that's why we're using Rust in the first place. To set or get any header, an object must implement the Header trait from this module. Several common headers are already provided, such as Host, ContentType, UserAgent, and others.

Why Typed?

Or, why not stringly-typed? Types give the following advantages:

  • More difficult to typo, since typos in types should be caught by the compiler
  • Parsing to a proper type by default

Defining Custom Headers

Implementing the Header trait

Consider a Do Not Track header. It can be true or false, but it represents that via the numerals 1 and 0.

extern crate http;
extern crate headers;

use headers::{Header, HeaderName, HeaderValue};

struct Dnt(bool);

impl Header for Dnt {
    fn name() -> &'static HeaderName {
         &http::header::DNT
    }

    fn decode<'i, I>(values: &mut I) -> Result<Self, headers::Error>
    where
        I: Iterator<Item = &'i HeaderValue>,
    {
        let value = values
            .next()
            .ok_or_else(headers::Error::invalid)?;

        if value == "0" {
            Ok(Dnt(false))
        } else if value == "1" {
            Ok(Dnt(true))
        } else {
            Err(headers::Error::invalid())
        }
    }

    fn encode<E>(&self, values: &mut E)
    where
        E: Extend<HeaderValue>,
    {
        let s = if self.0 {
            "1"
        } else {
            "0"
        };

        let value = HeaderValue::from_static(s);

        values.extend(std::iter::once(value));
    }
}

Dependencies

~1.5MB
~25K SLoC