rama_http/utils/
header_value.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use crate::{header::AsHeaderName, HeaderMap, Request, Response};

/// Utility trait for getting header values from a request or response.
pub trait HeaderValueGetter {
    /// Get a header value as a string.
    fn header_str<K>(&self, key: K) -> Result<&str, HeaderValueErr>
    where
        K: AsHeaderName + Copy;

    /// Get a header value as a byte slice.
    fn header_bytes<K>(&self, key: K) -> Result<&[u8], HeaderValueErr>
    where
        K: AsHeaderName + Copy;
}

impl<Body> HeaderValueGetter for Request<Body> {
    fn header_str<K>(&self, key: K) -> Result<&str, HeaderValueErr>
    where
        K: AsHeaderName + Copy,
    {
        self.headers().header_str(key)
    }

    fn header_bytes<K>(&self, key: K) -> Result<&[u8], HeaderValueErr>
    where
        K: AsHeaderName + Copy,
    {
        self.headers().header_bytes(key)
    }
}

impl<Body> HeaderValueGetter for Response<Body> {
    fn header_str<K>(&self, key: K) -> Result<&str, HeaderValueErr>
    where
        K: AsHeaderName + Copy,
    {
        self.headers().header_str(key)
    }

    fn header_bytes<K>(&self, key: K) -> Result<&[u8], HeaderValueErr>
    where
        K: AsHeaderName + Copy,
    {
        self.headers().header_bytes(key)
    }
}

impl HeaderValueGetter for HeaderMap {
    fn header_str<K>(&self, key: K) -> Result<&str, HeaderValueErr>
    where
        K: AsHeaderName + Copy,
    {
        match self.get(key) {
            Some(value) => value
                .to_str()
                .map_err(|_| HeaderValueErr::HeaderInvalid(key.as_str().to_owned())),
            None => Err(HeaderValueErr::HeaderMissing(key.as_str().to_owned())),
        }
    }

    fn header_bytes<K>(&self, key: K) -> Result<&[u8], HeaderValueErr>
    where
        K: AsHeaderName + Copy,
    {
        match self.get(key) {
            Some(value) => Ok(value.as_bytes()),
            None => Err(HeaderValueErr::HeaderMissing(key.as_str().to_owned())),
        }
    }
}

/// Error type for header value getters.
#[derive(Debug)]
pub enum HeaderValueErr {
    /// The header was missing.
    HeaderMissing(String),
    /// The header was invalid.
    HeaderInvalid(String),
}

impl std::fmt::Display for HeaderValueErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HeaderValueErr::HeaderMissing(key) => write!(f, "header missing: {}", key),
            HeaderValueErr::HeaderInvalid(key) => write!(f, "header invalid: {}", key),
        }
    }
}

impl std::error::Error for HeaderValueErr {}