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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use std::borrow::Cow;
use thiserror::Error;

#[derive(Debug, Error, Clone)]
#[non_exhaustive]
pub enum HttpRequestError {
    /// couldn't convert a http header value to string
    #[error("couldn't convert http header value to string for header key {key}")]
    HeaderValueToStr { key: String },

    /// unexpected error occurred
    #[error("unexpected error: {reason}")]
    Unexpected { reason: String },
}

pub trait HttpRequest {
    fn get_header_concatenated_values<'a>(&'a self, header_name: &str) -> Result<Cow<'a, str>, HttpRequestError>;
    fn get_lowercased_method(&self) -> Result<Cow<'_, str>, HttpRequestError>;
    fn get_target(&self) -> Result<Cow<'_, str>, HttpRequestError>;
}

#[cfg(feature = "http_trait_impl")]
mod http_trait_impl {
    use super::*;

    impl HttpRequest for http::request::Parts {
        fn get_header_concatenated_values<'a>(&'a self, header_name: &str) -> Result<Cow<'a, str>, HttpRequestError> {
            let mut values = Vec::new();
            let all_values = self.headers.get_all(header_name);
            for value in all_values {
                let value_str = value.to_str().map_err(|_| HttpRequestError::HeaderValueToStr {
                    key: header_name.to_owned(),
                })?;
                values.push(value_str.trim());
            }
            Ok(Cow::Owned(values.join(", ")))
        }

        fn get_lowercased_method(&self) -> Result<Cow<'_, str>, HttpRequestError> {
            Ok(Cow::Owned(self.method.as_str().to_lowercase()))
        }

        fn get_target(&self) -> Result<Cow<'_, str>, HttpRequestError> {
            Ok(Cow::Borrowed(self.uri.path()))
        }
    }
    impl<T> HttpRequest for http::request::Request<T> {
        fn get_header_concatenated_values<'a>(&'a self, header_name: &str) -> Result<Cow<'a, str>, HttpRequestError> {
            let mut values = Vec::new();
            let all_values = self.headers().get_all(header_name);
            for value in all_values {
                let value_str = value.to_str().map_err(|_| HttpRequestError::HeaderValueToStr {
                    key: header_name.to_owned(),
                })?;
                values.push(value_str.trim());
            }
            Ok(Cow::Owned(values.join(", ")))
        }

        fn get_lowercased_method(&self) -> Result<Cow<'_, str>, HttpRequestError> {
            Ok(Cow::Owned(self.method().as_str().to_lowercase()))
        }

        fn get_target(&self) -> Result<Cow<'_, str>, HttpRequestError> {
            Ok(Cow::Borrowed(self.uri().path()))
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use http::{header, method::Method, request};

        #[test]
        fn http_request_parts() {
            let req = request::Builder::new()
                .method(Method::GET)
                .uri("/foo")
                .header("Host", "example.org")
                .header(header::DATE, "Tue, 07 Jun 2014 20:51:35 GMT")
                .header("X-Example", " Example header       with some whitespace.   ")
                .header("X-EmptyHeader", "")
                .header(header::CACHE_CONTROL, "max-age=60")
                .header(header::CACHE_CONTROL, "must-revalidate")
                .body(())
                .expect("couldn't build request");

            let (parts, _) = req.into_parts();

            assert_eq!(parts.get_target().expect("target"), "/foo");
            assert_eq!(parts.get_lowercased_method().expect("method"), "get");
            assert_eq!(
                parts.get_header_concatenated_values("host").expect("host"),
                "example.org"
            );
            assert_eq!(
                parts.get_header_concatenated_values("date").expect("date"),
                "Tue, 07 Jun 2014 20:51:35 GMT"
            );
            assert_eq!(
                parts.get_header_concatenated_values("x-example").expect("example"),
                "Example header       with some whitespace."
            );
            assert_eq!(
                parts.get_header_concatenated_values("X-EmptyHeader").expect("empty"),
                ""
            );
            assert_eq!(
                parts
                    .get_header_concatenated_values(header::CACHE_CONTROL.as_str())
                    .expect("cache control"),
                "max-age=60, must-revalidate"
            );
        }

        #[test]
        fn http_request_request() {
            let req = request::Builder::new()
                .method(Method::GET)
                .uri("/foo")
                .header("Host", "example.org")
                .header(header::DATE, "Tue, 07 Jun 2014 20:51:35 GMT")
                .header("X-Example", " Example header       with some whitespace.   ")
                .header("X-EmptyHeader", "")
                .header(header::CACHE_CONTROL, "max-age=60")
                .header(header::CACHE_CONTROL, "must-revalidate")
                .body(())
                .expect("couldn't build request");

            assert_eq!(req.get_target().expect("target"), "/foo");
            assert_eq!(req.get_lowercased_method().expect("method"), "get");
            assert_eq!(req.get_header_concatenated_values("host").expect("host"), "example.org");
            assert_eq!(
                req.get_header_concatenated_values("date").expect("date"),
                "Tue, 07 Jun 2014 20:51:35 GMT"
            );
            assert_eq!(
                req.get_header_concatenated_values("x-example").expect("example"),
                "Example header       with some whitespace."
            );
            assert_eq!(req.get_header_concatenated_values("X-EmptyHeader").expect("empty"), "");
            assert_eq!(
                req.get_header_concatenated_values(header::CACHE_CONTROL.as_str())
                    .expect("cache control"),
                "max-age=60, must-revalidate"
            );
        }
    }
}