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
use async_std::io::prelude::*;
use http::StatusCode;
use http_service::Body;
use mime::Mime;
use serde::Serialize;
pub use into_response::IntoResponse;
mod into_response;
#[derive(Debug)]
pub struct Response {
res: http_service::Response,
}
impl Response {
pub fn new(status: u16) -> Self {
let status = http::StatusCode::from_u16(status).expect("invalid status code");
let res = http::Response::builder()
.status(status)
.body(Body::empty())
.unwrap();
Self { res }
}
pub fn with_reader<R>(status: u16, reader: R) -> Self
where
R: BufRead + Unpin + Send + 'static,
{
let status = http::StatusCode::from_u16(status).expect("invalid status code");
let res = http::Response::builder()
.status(status)
.body(Box::pin(reader).into())
.unwrap();
Self { res }
}
pub fn status(&self) -> http::StatusCode {
self.res.status()
}
pub fn set_status(mut self, status: http::StatusCode) -> Self {
*self.res.status_mut() = status;
self
}
pub fn set_header(mut self, key: &'static str, value: impl AsRef<str>) -> Self {
let value = value.as_ref().to_owned();
self.res.headers_mut().insert(key, value.parse().unwrap());
self
}
pub fn set_mime(self, mime: Mime) -> Self {
self.set_header("Content-Type", format!("{}", mime))
}
pub fn body_string(mut self, string: String) -> Self {
*self.res.body_mut() = string.into_bytes().into();
self.set_mime(mime::TEXT_PLAIN_UTF_8)
}
pub fn body<R>(mut self, reader: R) -> Self
where
R: BufRead + Unpin + Send + 'static,
{
*self.res.body_mut() = Box::pin(reader).into();
self.set_mime(mime::APPLICATION_OCTET_STREAM)
}
pub async fn body_form<T: serde::Serialize>(
mut self,
form: T,
) -> Result<Response, serde_qs::Error> {
*self.res.body_mut() = Body::from(serde_qs::to_string(&form)?.into_bytes());
Ok(self
.set_status(StatusCode::OK)
.set_header("Content-Type", "application/x-www-form-urlencoded"))
}
pub fn body_json(mut self, json: &impl Serialize) -> serde_json::Result<Self> {
*self.res.body_mut() = serde_json::to_vec(json)?.into();
Ok(self.set_mime(mime::APPLICATION_JSON))
}
}
#[doc(hidden)]
impl Into<http_service::Response> for Response {
fn into(self) -> http_service::Response {
self.res
}
}
#[doc(hidden)]
impl From<http_service::Response> for Response {
fn from(res: http_service::Response) -> Self {
Self { res }
}
}