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
use super::Mapper;
use crate::mappers::sequence::KV;
pub fn status_code<M>(inner: M) -> StatusCode<M> {
StatusCode(inner)
}
#[derive(Debug)]
pub struct StatusCode<M>(M);
impl<M, B> Mapper<http::Response<B>> for StatusCode<M>
where
M: Mapper<u16>,
{
type Out = M::Out;
fn map(&mut self, input: &http::Response<B>) -> M::Out {
self.0.map(&input.status().as_u16())
}
}
pub fn headers<M>(inner: M) -> Headers<M> {
Headers(inner)
}
#[derive(Debug)]
pub struct Headers<M>(M);
impl<M, B> Mapper<http::Response<B>> for Headers<M>
where
M: Mapper<[KV<str, [u8]>]>,
{
type Out = M::Out;
fn map(&mut self, input: &http::Response<B>) -> M::Out {
let headers: Vec<_> = input
.headers()
.iter()
.map(|(k, v)| KV {
k: k.as_str().to_owned(),
v: v.as_bytes().to_owned(),
})
.collect();
self.0.map(&headers)
}
}
pub fn body<M>(inner: M) -> Body<M> {
Body(inner)
}
#[derive(Debug)]
pub struct Body<M>(M);
impl<M, B> Mapper<http::Response<B>> for Body<M>
where
M: Mapper<B>,
{
type Out = M::Out;
fn map(&mut self, input: &http::Response<B>) -> M::Out {
self.0.map(input.body())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mappers::*;
#[test]
fn test_status_code() {
let resp = http::Response::builder()
.status(hyper::StatusCode::NOT_FOUND)
.body("")
.unwrap();
assert!(status_code(eq(404)).map(&resp));
let resp = http::Response::builder()
.status(hyper::StatusCode::OK)
.body("")
.unwrap();
assert!(status_code(eq(200)).map(&resp));
}
#[test]
fn test_headers() {
let expected: Vec<KV<str, [u8]>> = vec![
KV {
k: "host".to_owned(),
v: Vec::from("example.com"),
},
KV {
k: "content-length".to_owned(),
v: Vec::from("101"),
},
];
let resp = http::Response::builder()
.header("host", "example.com")
.header("content-length", 101)
.body("")
.unwrap();
assert!(headers(eq(expected)).map(&resp));
}
#[test]
fn test_body() {
let resp = http::Response::builder().body("my request body").unwrap();
assert!(body(eq("my request body")).map(&resp));
}
}