next_rust_server/
response.rs1use std::pin::Pin;
4
5use bytes::Bytes;
6use futures_util::stream::{Stream, StreamExt};
7use http::header::{CACHE_CONTROL, CONTENT_TYPE, HeaderName, HeaderValue, LOCATION};
8use http::{HeaderMap, StatusCode};
9use serde::Serialize;
10
11use crate::error::{Error, ErrorKind};
12use crate::request::BoxError;
13
14pub type ByteStream = Pin<Box<dyn Stream<Item = Result<Bytes, BoxError>> + Send + 'static>>;
15
16pub enum Body {
18 Empty,
19 Bytes(Bytes),
20 Stream(ByteStream),
21}
22
23impl std::fmt::Debug for Body {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 match self {
26 Body::Empty => f.write_str("Empty"),
27 Body::Bytes(b) => write!(f, "Bytes({})", b.len()),
28 Body::Stream(_) => f.write_str("Stream"),
29 }
30 }
31}
32
33#[derive(Debug)]
35pub struct Response {
36 pub status: StatusCode,
37 pub headers: HeaderMap,
38 pub body: Body,
39}
40
41impl Default for Response {
42 fn default() -> Self {
43 Response { status: StatusCode::OK, headers: HeaderMap::new(), body: Body::Empty }
44 }
45}
46
47impl Response {
48 pub fn new(status: StatusCode, body: Body) -> Self {
49 Response { status, headers: HeaderMap::new(), body }
50 }
51
52 pub fn status(code: u16) -> Self {
54 Response::new(StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), Body::Empty)
55 }
56
57 pub fn text(body: impl Into<String>) -> Self {
58 Response::new(StatusCode::OK, Body::Bytes(Bytes::from(body.into())))
59 .with_content_type("text/plain; charset=utf-8")
60 }
61
62 pub fn html(body: impl Into<String>) -> Self {
63 Response::new(StatusCode::OK, Body::Bytes(Bytes::from(body.into())))
64 .with_content_type("text/html; charset=utf-8")
65 }
66
67 pub fn json<T: Serialize + ?Sized>(data: &T) -> Self {
69 match serde_json::to_vec(data) {
70 Ok(v) => Response::new(StatusCode::OK, Body::Bytes(Bytes::from(v))).with_content_type("application/json"),
71 Err(e) => Error::from(e).into_response(),
72 }
73 }
74
75 pub fn bytes(body: impl Into<Bytes>) -> Self {
76 Response::new(StatusCode::OK, Body::Bytes(body.into())).with_content_type("application/octet-stream")
77 }
78
79 pub fn stream<S, B, E>(stream: S) -> Self
81 where
82 S: Stream<Item = Result<B, E>> + Send + 'static,
83 B: Into<Bytes>,
84 E: Into<BoxError>,
85 {
86 let s = stream.map(|r| r.map(Into::into).map_err(Into::into));
87 Response::new(StatusCode::OK, Body::Stream(Box::pin(s)))
88 }
89
90 pub fn redirect(location: &str) -> Self {
92 Response::redirect_with(location, StatusCode::TEMPORARY_REDIRECT)
93 }
94
95 pub fn permanent_redirect(location: &str) -> Self {
97 Response::redirect_with(location, StatusCode::PERMANENT_REDIRECT)
98 }
99
100 pub fn see_other(location: &str) -> Self {
102 Response::redirect_with(location, StatusCode::SEE_OTHER)
103 }
104
105 pub fn redirect_with(location: &str, status: StatusCode) -> Self {
106 let mut r = Response::new(status, Body::Empty);
107 match HeaderValue::from_str(location) {
108 Ok(v) => {
109 r.headers.insert(LOCATION, v);
110 }
111 Err(_) => return Response::status(500),
112 }
113 r
114 }
115
116 pub fn not_found() -> Self {
117 Response::text("Not Found").with_status(404)
118 }
119
120 pub fn with_status(mut self, code: u16) -> Self {
121 self.status = StatusCode::from_u16(code).unwrap_or(self.status);
122 self
123 }
124
125 pub fn with_header(mut self, name: &str, value: &str) -> Self {
128 self.set_header(name, value);
129 self
130 }
131
132 pub fn set_header(&mut self, name: &str, value: &str) -> bool {
133 match (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) {
134 (Ok(n), Ok(v)) => {
135 self.headers.insert(n, v);
136 true
137 }
138 _ => {
139 crate::log::warn(&format!("invalid response header {name:?} dropped"));
140 false
141 }
142 }
143 }
144
145 pub fn append_header(&mut self, name: &str, value: &str) -> bool {
146 match (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) {
147 (Ok(n), Ok(v)) => {
148 self.headers.append(n, v);
149 true
150 }
151 _ => false,
152 }
153 }
154
155 pub fn with_content_type(mut self, ct: &'static str) -> Self {
156 self.headers.insert(CONTENT_TYPE, HeaderValue::from_static(ct));
157 self
158 }
159
160 pub fn with_cache_control(mut self, value: &str) -> Self {
161 if let Ok(v) = HeaderValue::from_str(value) {
162 self.headers.insert(CACHE_CONTROL, v);
163 }
164 self
165 }
166
167 pub fn with_cookie(mut self, cookie: crate::Cookie) -> Self {
169 match cookie.to_header_value() {
170 Ok(v) => {
171 self.append_header("set-cookie", &v);
172 }
173 Err(e) => crate::log::warn(&format!("cookie not sent: {e}")),
174 }
175 self
176 }
177
178 pub fn header(&self, name: &str) -> Option<&str> {
179 self.headers.get(name).and_then(|v| v.to_str().ok())
180 }
181
182 pub async fn into_bytes(self) -> Result<Bytes, BoxError> {
184 match self.body {
185 Body::Empty => Ok(Bytes::new()),
186 Body::Bytes(b) => Ok(b),
187 Body::Stream(mut s) => {
188 let mut buf = Vec::new();
189 while let Some(chunk) = s.next().await {
190 buf.extend_from_slice(&chunk?);
191 }
192 Ok(Bytes::from(buf))
193 }
194 }
195 }
196
197 pub async fn into_text(self) -> String {
199 match self.into_bytes().await {
200 Ok(b) => String::from_utf8_lossy(&b).into_owned(),
201 Err(e) => format!("<body error: {e}>"),
202 }
203 }
204}
205
206pub trait IntoResponse {
208 fn into_response(self) -> Response;
209}
210
211impl IntoResponse for Response {
212 fn into_response(self) -> Response {
213 self
214 }
215}
216
217impl IntoResponse for &'static str {
218 fn into_response(self) -> Response {
219 Response::text(self)
220 }
221}
222
223impl IntoResponse for String {
224 fn into_response(self) -> Response {
225 Response::text(self)
226 }
227}
228
229impl IntoResponse for Bytes {
230 fn into_response(self) -> Response {
231 Response::bytes(self)
232 }
233}
234
235impl IntoResponse for Vec<u8> {
236 fn into_response(self) -> Response {
237 Response::bytes(self)
238 }
239}
240
241impl IntoResponse for () {
242 fn into_response(self) -> Response {
243 Response::status(204)
244 }
245}
246
247impl IntoResponse for StatusCode {
248 fn into_response(self) -> Response {
249 Response::new(self, Body::Empty)
250 }
251}
252
253impl<T: IntoResponse> IntoResponse for (StatusCode, T) {
254 fn into_response(self) -> Response {
255 let mut r = self.1.into_response();
256 r.status = self.0;
257 r
258 }
259}
260
261impl<T: IntoResponse, E: Into<Error>> IntoResponse for Result<T, E> {
262 fn into_response(self) -> Response {
263 match self {
264 Ok(v) => v.into_response(),
265 Err(e) => e.into().into_response(),
266 }
267 }
268}
269
270pub struct Json<T>(pub T);
272
273impl<T: Serialize> IntoResponse for Json<T> {
274 fn into_response(self) -> Response {
275 Response::json(&self.0)
276 }
277}
278
279pub struct Html<T>(pub T);
281
282impl<T: Into<String>> IntoResponse for Html<T> {
283 fn into_response(self) -> Response {
284 Response::html(self.0)
285 }
286}
287
288impl IntoResponse for Error {
289 fn into_response(self) -> Response {
290 let status = self.status();
291 match self.into_kind() {
292 ErrorKind::Redirect { location, status } => Response::redirect_with(&location, status),
293 ErrorKind::Validation(fields) => {
294 let mut r = Response::json(&serde_json::json!({ "error": "validation failed", "fields": fields }));
295 r.status = status;
296 r
297 }
298 kind => {
299 let err = Error::new(kind);
300 if status.is_server_error() {
301 crate::log::error(&format!("request failed: {}", err.detailed_message()));
302 }
303 let msg = if crate::is_dev() { err.detailed_message() } else { err.public_message() };
304 let mut r = Response::text(msg);
305 r.status = status;
306 r
307 }
308 }
309 }
310}