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
use crate::bindings::HttpResponse;
use crate::http::{Body, Status};
#[derive(Default, Debug)]
pub struct ResponseBuilder(pub(crate) HttpResponse);
impl ResponseBuilder {
pub fn new() -> ResponseBuilder {
ResponseBuilder(HttpResponse::new())
}
pub fn status<S: Into<Status>>(mut self, status: S) -> Self {
self.0.status = status.into();
self
}
pub fn header<T: Into<String>, U: Into<String>>(mut self, name: T, value: U) -> Self {
self.0.data.mut_headers().insert(name.into(), value.into());
self
}
pub fn body<'a, B>(mut self, body: B) -> Self
where
B: Into<Body<'a>>,
{
let body = body.into();
if let Body::Empty = &body {
self.0.data.clear_body();
return self;
}
if !self.0.headers().contains_key("Content-Type") {
self.0.data.mut_headers().insert(
"Content-Type".to_string(),
body.default_content_type().to_string(),
);
}
self.0.data.set_body(body.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_creates_an_empty_response() {
let response: HttpResponse = ResponseBuilder::new().into();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body().as_str().unwrap(), "");
}
#[test]
fn it_sets_a_status() {
let response: HttpResponse = ResponseBuilder::new().status(Status::BadRequest).into();
assert_eq!(response.status(), Status::BadRequest);
assert_eq!(response.body().as_str().unwrap(), "");
}
#[test]
fn it_sets_a_header() {
let response: HttpResponse = ResponseBuilder::new().header("foo", "bar").into();
assert_eq!(response.headers().get("foo").unwrap(), "bar");
assert_eq!(response.body().as_str().unwrap(), "");
}
#[test]
fn it_sets_a_body() {
let response: HttpResponse = ResponseBuilder::new().body("test").into();
assert_eq!(
response.headers().get("Content-Type").unwrap(),
"text/plain"
);
assert_eq!(response.body().as_str().unwrap(), "test");
}
}