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

时间:2018-02-16 20:07:42

标签: rust hyper

我更愿意利用Hyper hyper::header::Headers#get方法的类型安全性,而不是&str使用get_raw

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

通过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] }

在范围内获得名为Response的{​​{1}}后,您可以像这样访问此标头:

res