我更愿意利用 Hyperhyper::header::Headers#get
方法的类型安全性,而不是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] }
一旦你在范围内有了一个Response
命名res
,你可以像这样访问这个标头:
let arbitrary_header: AribitraryNumber = res.headers().get::<ArbitraryNumberHeader>().unwrap();