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
#[cfg(feature = "json")]
use bytes::{BufMut, BytesMut};
use crate::{header, Body, Response, Result, StatusCode};
pub trait ResponseExt: Sized {
fn with<T>(t: T, c: &'static str) -> Response
where
T: Into<Body>,
{
let mut res = Response::new(t.into());
res.headers_mut()
.insert(header::CONTENT_TYPE, header::HeaderValue::from_static(c));
res
}
fn text<T>(t: T) -> Response
where
T: Into<Body>,
{
Self::with(t, mime::TEXT_PLAIN_UTF_8.as_ref())
}
fn html<T>(t: T) -> Response
where
T: Into<Body>,
{
Self::with(t, mime::TEXT_HTML_UTF_8.as_ref())
}
#[cfg(feature = "json")]
fn json<T>(t: T) -> Result<Response, crate::types::PayloadError>
where
T: serde::Serialize,
{
let mut buf = BytesMut::new().writer();
serde_json::to_writer(&mut buf, &t)
.map(|_| Self::with(buf.into_inner().freeze(), mime::APPLICATION_JSON.as_ref()))
.map_err(crate::types::PayloadError::Json)
}
fn stream<S, O, E>(s: S) -> Response
where
S: futures_util::Stream<Item = Result<O, E>> + Send + 'static,
O: Into<bytes::Bytes> + 'static,
E: std::error::Error + Send + Sync + 'static,
{
Response::new(Body::wrap_stream(s))
}
fn ok(&self) -> bool;
fn location(location: &'static str) -> Self;
fn redirect<T>(url: T) -> Response
where
T: AsRef<str>;
fn redirect_with_status<T>(uri: T, status: StatusCode) -> Response
where
T: AsRef<str>;
fn see_other<T>(url: T) -> Response
where
T: AsRef<str>,
{
Self::redirect_with_status(url, StatusCode::SEE_OTHER)
}
fn temporary<T>(url: T) -> Response
where
T: AsRef<str>,
{
Self::redirect_with_status(url, StatusCode::TEMPORARY_REDIRECT)
}
fn permanent<T>(url: T) -> Response
where
T: AsRef<str>,
{
Self::redirect_with_status(url, StatusCode::PERMANENT_REDIRECT)
}
}
impl ResponseExt for Response {
fn ok(&self) -> bool {
self.status().is_success()
}
fn location(location: &'static str) -> Self {
let mut res = Self::default();
res.headers_mut().insert(
header::CONTENT_LOCATION,
header::HeaderValue::from_static(location),
);
res
}
fn redirect<T>(url: T) -> Response
where
T: AsRef<str>,
{
match header::HeaderValue::try_from(url.as_ref()) {
Ok(val) => {
let mut res = Self::default();
res.headers_mut().insert(header::LOCATION, val);
res
}
Err(err) => panic!("{}", err),
}
}
fn redirect_with_status<T>(url: T, status: StatusCode) -> Response
where
T: AsRef<str>,
{
assert!(status.is_redirection(), "not a redirection status code");
let mut res = Self::redirect(url);
*res.status_mut() = status;
res
}
}