//! Mappers that extract information from HTTP responses. use super::Mapper; /// Extract the status code from the HTTP response and pass it to the next mapper. pub fn status_code(inner: C) -> StatusCode { StatusCode(inner) } /// The `StatusCode` mapper returned by [status_code()](fn.status_code.html) #[derive(Debug)] pub struct StatusCode(C); impl Mapper> for StatusCode where C: Mapper, { type Out = C::Out; fn map(&mut self, input: &hyper::Response) -> C::Out { self.0.map(&input.status().as_u16()) } } /// Extract the headers from the HTTP response and pass the sequence to the next /// mapper. pub fn headers(inner: C) -> Headers { Headers(inner) } /// The `Headers` mapper returned by [headers()](fn.headers.html) #[derive(Debug)] pub struct Headers(C); impl Mapper> for Headers where C: Mapper<[(Vec, Vec)]>, { type Out = C::Out; fn map(&mut self, input: &hyper::Response) -> C::Out { let headers: Vec<(Vec, Vec)> = input .headers() .iter() .map(|(k, v)| (k.as_str().into(), v.as_bytes().into())) .collect(); self.0.map(&headers) } } /// Extract the body from the HTTP response and pass it to the next mapper. pub fn body(inner: C) -> Body { Body(inner) } /// The `Body` mapper returned by [body()](fn.body.html) #[derive(Debug)] pub struct Body(C); impl Mapper> for Body where C: Mapper, { type Out = C::Out; fn map(&mut self, input: &hyper::Response) -> C::Out { self.0.map(input.body()) } } #[cfg(test)] mod tests { use super::*; use crate::mappers::*; #[test] fn test_status_code() { let resp = hyper::Response::builder() .status(hyper::StatusCode::NOT_FOUND) .body("") .unwrap(); assert!(status_code(eq(404)).map(&resp)); let resp = hyper::Response::builder() .status(hyper::StatusCode::OK) .body("") .unwrap(); assert!(status_code(eq(200)).map(&resp)); } #[test] fn test_headers() { let expected = vec![ (Vec::from("host"), Vec::from("example.com")), (Vec::from("content-length"), Vec::from("101")), ]; let resp = hyper::Response::builder() .header("host", "example.com") .header("content-length", 101) .body("") .unwrap(); assert!(headers(eq(expected)).map(&resp)); } #[test] fn test_body() { let resp = hyper::Response::builder().body("my request body").unwrap(); assert!(body(eq("my request body")).map(&resp)); } }