7 releases

new 0.3.1 Jan 24, 2020
0.3.0 Dec 12, 2019
0.2.3 Sep 9, 2019
0.2.1 Feb 1, 2019
0.1.0 Aug 9, 2016

#137 in Web programming

Download history 5548/week @ 2019-10-07 5593/week @ 2019-10-14 6078/week @ 2019-10-21 5843/week @ 2019-10-28 7259/week @ 2019-11-04 6386/week @ 2019-11-11 8812/week @ 2019-11-18 6681/week @ 2019-11-25 7791/week @ 2019-12-02 10153/week @ 2019-12-09 9000/week @ 2019-12-16 3690/week @ 2019-12-23 4513/week @ 2019-12-30 9561/week @ 2020-01-06 10807/week @ 2020-01-13

32,856 downloads per month
Used in 54 crates (9 directly)

MIT license

305KB
5.5K 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
~29K SLoC