如何实现自定义类型 header 以用于 Hyper?

How can I implement a custom typed header for use with Hyper?

我更愿意利用 Hyper hyper::header::Headers#get method instead of using get_raw 的类型安全和 &str

完成此任务的最佳方法是什么?

通过 hyper::header::Headers 源代码挖掘,我发现有一个简洁的宏用于生成代码:header!。不过,您需要一些咒语才能使它有用:

#[macro_use]
extern crate hyper;

use hyper::{Body, Method, Request, Response};
use std::fmt::{self, Display};
use std::str::FromStr;
use std::num::ParseIntError;

// For a header that looks like this:
//    x-arbitrary-header-with-an-integer: 8

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArbitraryNumber(i8);

impl Display for ArbitraryNumber {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Arbitrary Protocol v{}", self.0)
    }
}

impl FromStr for ArbitraryNumber {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<i8>().map(|int| ArbitraryNumber(int))
    }
}

//impl Header for ArbitraryNumberHeader
header! { (ArbitraryNumberHeader, "x-arbitrary-header-with-an-integer") => [ArbitraryNumber] }

一旦你在范围内获得了一个名为 resResponse,你就可以像这样访问这个 header:

let arbitrary_header: AribitraryNumber = res.headers().get::<ArbitraryNumberHeader>().unwrap();