hyper_old_types

Module header

Source
Expand description

Headers container, and common header fields.

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

Hyper provides many of the most commonly used headers in HTTP. If you need to define a custom header, it’s easy to do while still taking advantage of the type system. Hyper includes a header! macro for defining many wrapper-style headers.

#[macro_use] extern crate hyper;
use hyper::header::Headers;
header! { (XRequestGuid, "X-Request-Guid") => [String] }

fn main () {
    let mut headers = Headers::new();

    headers.set(XRequestGuid("a proper guid".to_owned()))
}

This works well for simple “string” headers. If you need more control, you can implement the trait directly.

§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.

use std::fmt;
use hyper::header::{self, Header, Raw};

#[derive(Debug, Clone, Copy)]
struct Dnt(bool);

impl Header for Dnt {
    fn header_name() -> &'static str {
        "DNT"
    }

    fn parse_header(raw: &Raw) -> hyper::Result<Dnt> {
        if raw.len() == 1 {
            let line = &raw[0];
            if line.len() == 1 {
                let byte = line[0];
                match byte {
                    b'0' => return Ok(Dnt(true)),
                    b'1' => return Ok(Dnt(false)),
                    _ => ()
                }
            }
        }
        Err(hyper::Error::Header)
    }

    fn fmt_header(&self, f: &mut header::Formatter) -> fmt::Result {
        let value = if self.0 {
            "1"
        } else {
            "0"
        };
        f.fmt_line(&value)
    }
}

Modules§

  • Utility functions for Header implementations.

Macros§

Structs§

Enums§

Traits§

  • A trait for any object that will represent a header field and value.
  • An Authorization scheme to be used in the header.

Functions§

  • Convenience function to create a Quality from a float or integer.
  • Convenience function to wrap a value in a QualityItem Sets q to the default 1.0