Skip to main content

next_rust_server/
response.rs

1//! Outgoing HTTP response.
2
3use 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
16/// Response body.
17pub 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/// An HTTP response.
34#[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    /// Empty response with a status code.
53    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    /// XML response (feeds, sitemaps).
68    pub fn xml(body: impl Into<String>) -> Self {
69        Response::new(StatusCode::OK, Body::Bytes(Bytes::from(body.into())))
70            .with_content_type("application/xml; charset=utf-8")
71    }
72
73    /// SVG response, for images generated on the fly.
74    pub fn svg(body: impl Into<String>) -> Self {
75        Response::new(StatusCode::OK, Body::Bytes(Bytes::from(body.into())))
76            .with_content_type("image/svg+xml; charset=utf-8")
77    }
78
79    /// JSON response. Serialization failures produce a 500.
80    pub fn json<T: Serialize + ?Sized>(data: &T) -> Self {
81        match serde_json::to_vec(data) {
82            Ok(v) => Response::new(StatusCode::OK, Body::Bytes(Bytes::from(v))).with_content_type("application/json"),
83            Err(e) => Error::from(e).into_response(),
84        }
85    }
86
87    pub fn bytes(body: impl Into<Bytes>) -> Self {
88        Response::new(StatusCode::OK, Body::Bytes(body.into())).with_content_type("application/octet-stream")
89    }
90
91    /// Stream arbitrary byte chunks.
92    pub fn stream<S, B, E>(stream: S) -> Self
93    where
94        S: Stream<Item = Result<B, E>> + Send + 'static,
95        B: Into<Bytes>,
96        E: Into<BoxError>,
97    {
98        let s = stream.map(|r| r.map(Into::into).map_err(Into::into));
99        Response::new(StatusCode::OK, Body::Stream(Box::pin(s)))
100    }
101
102    /// Temporary redirect (307).
103    pub fn redirect(location: &str) -> Self {
104        Response::redirect_with(location, StatusCode::TEMPORARY_REDIRECT)
105    }
106
107    /// Permanent redirect (308).
108    pub fn permanent_redirect(location: &str) -> Self {
109        Response::redirect_with(location, StatusCode::PERMANENT_REDIRECT)
110    }
111
112    /// Redirect after a form POST (303 See Other).
113    pub fn see_other(location: &str) -> Self {
114        Response::redirect_with(location, StatusCode::SEE_OTHER)
115    }
116
117    pub fn redirect_with(location: &str, status: StatusCode) -> Self {
118        let mut r = Response::new(status, Body::Empty);
119        match HeaderValue::from_str(location) {
120            Ok(v) => {
121                r.headers.insert(LOCATION, v);
122            }
123            Err(_) => return Response::status(500),
124        }
125        r
126    }
127
128    pub fn not_found() -> Self {
129        Response::text("Not Found").with_status(404)
130    }
131
132    pub fn with_status(mut self, code: u16) -> Self {
133        self.status = StatusCode::from_u16(code).unwrap_or(self.status);
134        self
135    }
136
137    /// Set a header. Invalid names or values (e.g. containing CR/LF) are
138    /// rejected, which prevents header injection; they are logged and dropped.
139    pub fn with_header(mut self, name: &str, value: &str) -> Self {
140        self.set_header(name, value);
141        self
142    }
143
144    pub fn set_header(&mut self, name: &str, value: &str) -> bool {
145        match (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) {
146            (Ok(n), Ok(v)) => {
147                self.headers.insert(n, v);
148                true
149            }
150            _ => {
151                crate::log::warn(&format!("invalid response header {name:?} dropped"));
152                false
153            }
154        }
155    }
156
157    pub fn append_header(&mut self, name: &str, value: &str) -> bool {
158        match (HeaderName::from_bytes(name.as_bytes()), HeaderValue::from_str(value)) {
159            (Ok(n), Ok(v)) => {
160                self.headers.append(n, v);
161                true
162            }
163            _ => false,
164        }
165    }
166
167    pub fn with_content_type(mut self, ct: &'static str) -> Self {
168        self.headers.insert(CONTENT_TYPE, HeaderValue::from_static(ct));
169        self
170    }
171
172    pub fn with_cache_control(mut self, value: &str) -> Self {
173        if let Ok(v) = HeaderValue::from_str(value) {
174            self.headers.insert(CACHE_CONTROL, v);
175        }
176        self
177    }
178
179    /// Add a cookie to the response.
180    pub fn with_cookie(mut self, cookie: crate::Cookie) -> Self {
181        match cookie.to_header_value() {
182            Ok(v) => {
183                self.append_header("set-cookie", &v);
184            }
185            Err(e) => crate::log::warn(&format!("cookie not sent: {e}")),
186        }
187        self
188    }
189
190    pub fn header(&self, name: &str) -> Option<&str> {
191        self.headers.get(name).and_then(|v| v.to_str().ok())
192    }
193
194    /// Collect the body into bytes (tests and adapters).
195    pub async fn into_bytes(self) -> Result<Bytes, BoxError> {
196        match self.body {
197            Body::Empty => Ok(Bytes::new()),
198            Body::Bytes(b) => Ok(b),
199            Body::Stream(mut s) => {
200                let mut buf = Vec::new();
201                while let Some(chunk) = s.next().await {
202                    buf.extend_from_slice(&chunk?);
203                }
204                Ok(Bytes::from(buf))
205            }
206        }
207    }
208
209    /// Collect the body as UTF-8 text (lossy).
210    pub async fn into_text(self) -> String {
211        match self.into_bytes().await {
212            Ok(b) => String::from_utf8_lossy(&b).into_owned(),
213            Err(e) => format!("<body error: {e}>"),
214        }
215    }
216}
217
218/// Conversion into a [`Response`].
219pub trait IntoResponse {
220    fn into_response(self) -> Response;
221}
222
223impl IntoResponse for Response {
224    fn into_response(self) -> Response {
225        self
226    }
227}
228
229impl IntoResponse for &'static str {
230    fn into_response(self) -> Response {
231        Response::text(self)
232    }
233}
234
235impl IntoResponse for String {
236    fn into_response(self) -> Response {
237        Response::text(self)
238    }
239}
240
241impl IntoResponse for Bytes {
242    fn into_response(self) -> Response {
243        Response::bytes(self)
244    }
245}
246
247impl IntoResponse for Vec<u8> {
248    fn into_response(self) -> Response {
249        Response::bytes(self)
250    }
251}
252
253impl IntoResponse for () {
254    fn into_response(self) -> Response {
255        Response::status(204)
256    }
257}
258
259impl IntoResponse for StatusCode {
260    fn into_response(self) -> Response {
261        Response::new(self, Body::Empty)
262    }
263}
264
265impl<T: IntoResponse> IntoResponse for (StatusCode, T) {
266    fn into_response(self) -> Response {
267        let mut r = self.1.into_response();
268        r.status = self.0;
269        r
270    }
271}
272
273impl<T: IntoResponse, E: Into<Error>> IntoResponse for Result<T, E> {
274    fn into_response(self) -> Response {
275        match self {
276            Ok(v) => v.into_response(),
277            Err(e) => e.into().into_response(),
278        }
279    }
280}
281
282/// JSON body wrapper: `Json(data)`.
283pub struct Json<T>(pub T);
284
285impl<T: Serialize> IntoResponse for Json<T> {
286    fn into_response(self) -> Response {
287        Response::json(&self.0)
288    }
289}
290
291/// HTML body wrapper: `Html(markup)`.
292pub struct Html<T>(pub T);
293
294impl<T: Into<String>> IntoResponse for Html<T> {
295    fn into_response(self) -> Response {
296        Response::html(self.0)
297    }
298}
299
300impl IntoResponse for Error {
301    fn into_response(self) -> Response {
302        let status = self.status();
303        match self.into_kind() {
304            ErrorKind::Redirect { location, status } => Response::redirect_with(&location, status),
305            ErrorKind::Validation(fields) => {
306                let mut r = Response::json(&serde_json::json!({ "error": "validation failed", "fields": fields }));
307                r.status = status;
308                r
309            }
310            kind => {
311                let err = Error::new(kind);
312                if status.is_server_error() {
313                    crate::log::error(&format!("request failed: {}", err.detailed_message()));
314                }
315                let msg = if crate::is_dev() { err.detailed_message() } else { err.public_message() };
316                let mut r = Response::text(msg);
317                r.status = status;
318                r
319            }
320        }
321    }
322}