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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use futures_util::future::{self, BoxFuture, FutureExt};
use gotham::{
handler::HandlerError,
hyper::{
header::{HeaderMap, HeaderName, HeaderValue},
Body, StatusCode
},
mime::{Mime, APPLICATION_JSON, STAR_STAR}
};
#[cfg(feature = "openapi")]
use openapi_type::{OpenapiSchema, OpenapiType};
use serde::Serialize;
use std::{
convert::Infallible,
fmt::{Debug, Display},
future::Future,
pin::Pin
};
mod auth_result;
#[allow(unreachable_pub)]
pub use auth_result::{AuthError, AuthErrorOrOther, AuthResult, AuthSuccess};
mod no_content;
#[allow(unreachable_pub)]
pub use no_content::NoContent;
mod raw;
#[allow(unreachable_pub)]
pub use raw::Raw;
mod redirect;
#[allow(unreachable_pub)]
pub use redirect::Redirect;
mod result;
#[allow(unreachable_pub)]
pub use result::IntoResponseError;
mod success;
#[allow(unreachable_pub)]
pub use success::Success;
pub(crate) trait OrAllTypes {
fn or_all_types(self) -> Vec<Mime>;
}
impl OrAllTypes for Option<Vec<Mime>> {
fn or_all_types(self) -> Vec<Mime> {
self.unwrap_or_else(|| vec![STAR_STAR])
}
}
#[derive(Debug)]
pub struct Response {
pub(crate) status: StatusCode,
pub(crate) body: Body,
pub(crate) mime: Option<Mime>,
pub(crate) headers: HeaderMap
}
impl Response {
#[must_use = "Creating a response is pointless if you don't use it"]
pub fn new<B: Into<Body>>(status: StatusCode, body: B, mime: Option<Mime>) -> Self {
Self {
status,
body: body.into(),
mime,
headers: Default::default()
}
}
#[must_use = "Creating a response is pointless if you don't use it"]
pub fn json<B: Into<Body>>(status: StatusCode, body: B) -> Self {
Self {
status,
body: body.into(),
mime: Some(APPLICATION_JSON),
headers: Default::default()
}
}
#[must_use = "Creating a response is pointless if you don't use it"]
pub fn no_content() -> Self {
Self {
status: StatusCode::NO_CONTENT,
body: Body::empty(),
mime: None,
headers: Default::default()
}
}
#[must_use = "Creating a response is pointless if you don't use it"]
pub fn forbidden() -> Self {
Self {
status: StatusCode::FORBIDDEN,
body: Body::empty(),
mime: None,
headers: Default::default()
}
}
pub fn status(&self) -> StatusCode {
self.status
}
pub fn mime(&self) -> Option<&Mime> {
self.mime.as_ref()
}
pub fn header(&mut self, name: HeaderName, value: HeaderValue) {
self.headers.insert(name, value);
}
pub(crate) fn with_headers(mut self, headers: HeaderMap) -> Self {
self.headers = headers;
self
}
#[cfg(test)]
pub(crate) fn full_body(mut self) -> Result<Vec<u8>, <Body as gotham::hyper::body::HttpBody>::Error> {
use futures_executor::block_on;
use gotham::hyper::body::to_bytes;
let bytes: &[u8] = &block_on(to_bytes(&mut self.body))?;
Ok(bytes.to_vec())
}
}
impl IntoResponse for Response {
type Err = Infallible;
fn into_response(self) -> BoxFuture<'static, Result<Response, Self::Err>> {
future::ok(self).boxed()
}
}
pub trait IntoResponse {
type Err: Into<HandlerError> + Send + Sync + 'static;
fn into_response(self) -> BoxFuture<'static, Result<Response, Self::Err>>;
fn accepted_types() -> Option<Vec<Mime>> {
None
}
}
#[cfg(feature = "openapi")]
pub trait ResponseSchema {
fn status_codes() -> Vec<StatusCode> {
vec![StatusCode::OK]
}
fn schema(code: StatusCode) -> OpenapiSchema;
}
#[cfg(feature = "openapi")]
mod private {
pub trait Sealed {}
}
#[cfg(feature = "openapi")]
pub trait IntoResponseWithSchema: IntoResponse + ResponseSchema + private::Sealed {}
#[cfg(feature = "openapi")]
impl<R: IntoResponse + ResponseSchema> private::Sealed for R {}
#[cfg(feature = "openapi")]
impl<R: IntoResponse + ResponseSchema> IntoResponseWithSchema for R {}
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
pub(crate) struct ResourceError {
error: bool,
message: String
}
impl<T: ToString> From<T> for ResourceError {
fn from(message: T) -> Self {
Self {
error: true,
message: message.to_string()
}
}
}
#[cfg(feature = "errorlog")]
fn errorlog<E: Display>(e: E) {
error!("The handler encountered an error: {}", e);
}
#[cfg(not(feature = "errorlog"))]
fn errorlog<E>(_e: E) {}
fn handle_error<E>(e: E) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
where
E: Display + IntoResponseError
{
let msg = e.to_string();
let res = e.into_response_error();
match &res {
Ok(res) if res.status.is_server_error() => errorlog(msg),
Err(err) => {
errorlog(msg);
errorlog(&err);
},
_ => {}
};
future::ready(res).boxed()
}
impl<Res> IntoResponse for Pin<Box<dyn Future<Output = Res> + Send>>
where
Res: IntoResponse + 'static
{
type Err = Res::Err;
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>> {
self.then(IntoResponse::into_response).boxed()
}
fn accepted_types() -> Option<Vec<Mime>> {
Res::accepted_types()
}
}
#[cfg(feature = "openapi")]
impl<Res> ResponseSchema for Pin<Box<dyn Future<Output = Res> + Send>>
where
Res: ResponseSchema
{
fn status_codes() -> Vec<StatusCode> {
Res::status_codes()
}
fn schema(code: StatusCode) -> OpenapiSchema {
Res::schema(code)
}
}
#[cfg(test)]
mod test {
use super::*;
use futures_executor::block_on;
use thiserror::Error;
#[derive(Debug, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "openapi", derive(openapi_type::OpenapiType))]
struct Msg {
msg: String
}
#[derive(Debug, Default, Error)]
#[error("An Error")]
struct MsgError;
#[test]
fn result_from_future() {
let nc = NoContent::default();
let res = block_on(nc.into_response()).unwrap();
let fut_nc = async move { NoContent::default() }.boxed();
let fut_res = block_on(fut_nc.into_response()).unwrap();
assert_eq!(res.status, fut_res.status);
assert_eq!(res.mime, fut_res.mime);
assert_eq!(res.full_body().unwrap(), fut_res.full_body().unwrap());
}
}