【问题标题】:How can I implement a custom typed header for use with Hyper?如何实现自定义类型的标头以与 Hyper 一起使用?
【发布时间】:2018-02-17 05:14:47
【问题描述】:

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

最好的方法是什么?

【问题讨论】:

    标签: rust hyper


    【解决方案1】:

    翻阅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,你就可以像这样访问这个标头:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      相关资源
      最近更新 更多