1use bytes::Bytes;
4use http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode, header};
5use http_body_util::Full;
6use serde::Serialize;
7
8use crate::error::Error;
9
10#[derive(Debug, Clone, Copy)]
12struct Head;
13
14#[derive(Debug, Clone)]
16pub struct Response {
17 status: StatusCode,
18 headers: HeaderMap,
19 body: Bytes,
20 extensions: Extensions,
21}
22
23impl Default for Response {
24 fn default() -> Self {
25 Self::new(StatusCode::OK)
26 }
27}
28
29impl Response {
30 pub fn new(status: StatusCode) -> Self {
32 Self {
33 status,
34 headers: HeaderMap::new(),
35 body: Bytes::new(),
36 extensions: Extensions::new(),
37 }
38 }
39
40 pub fn text(body: impl Into<String>) -> Self {
41 Self::with_body(body.into(), "text/plain; charset=utf-8")
42 }
43
44 pub fn html(body: impl Into<String>) -> Self {
45 let mut body = body.into();
46 if crate::view::reload::enabled()
48 && let Some(at) = body.rfind("</body>")
49 {
50 body.insert_str(at, &crate::view::reload::script());
51 }
52 Self::with_body(body, "text/html; charset=utf-8")
53 }
54
55 pub fn json<T: Serialize + ?Sized>(value: &T) -> Self {
59 match serde_json::to_vec(value) {
60 Ok(body) if ESCAPE_HTML.load(std::sync::atomic::Ordering::Relaxed) => {
61 Self::with_body(escape_html(&body), "application/json; charset=utf-8")
62 }
63 Ok(body) => Self::with_body(body, "application/json; charset=utf-8"),
64 Err(err) => Error::from(err).into_response(),
65 }
66 }
67
68 pub fn redirect(location: &str) -> Self {
70 Self::new(StatusCode::SEE_OTHER).with_header(header::LOCATION, location)
71 }
72
73 pub fn download(bytes: impl Into<Bytes>, filename: &str) -> Self {
77 Self::send_data(bytes, filename, "attachment")
78 }
79
80 pub fn inline(bytes: impl Into<Bytes>, filename: &str) -> Self {
83 Self::send_data(bytes, filename, "inline")
84 }
85
86 fn send_data(bytes: impl Into<Bytes>, filename: &str, disposition: &str) -> Self {
87 let extension = filename
88 .rsplit_once('.')
89 .map(|(_, ext)| ext.to_ascii_lowercase());
90 let content_type = extension
91 .as_deref()
92 .and_then(crate::mime::for_format)
93 .unwrap_or("application/octet-stream");
94 let ascii: String = filename
96 .chars()
97 .map(|c| {
98 if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' {
99 c
100 } else {
101 '_'
102 }
103 })
104 .collect();
105 const UNRESERVED: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
106 .remove(b'-')
107 .remove(b'.')
108 .remove(b'_')
109 .remove(b'~');
110 let exact = percent_encoding::utf8_percent_encode(filename, UNRESERVED);
111 Self::new(StatusCode::OK)
112 .with_body_bytes(bytes)
113 .with_header(header::CONTENT_TYPE, content_type)
114 .with_header(
115 header::CONTENT_DISPOSITION,
116 format!("{disposition}; filename=\"{ascii}\"; filename*=UTF-8''{exact}"),
117 )
118 }
119
120 pub fn head(status: StatusCode) -> Self {
123 let mut response = Self::new(status);
124 response.extensions.insert(Head);
125 response
126 }
127
128 pub fn no_content() -> Self {
129 Self::new(StatusCode::NO_CONTENT)
130 }
131
132 fn with_body(body: impl Into<Bytes>, content_type: &'static str) -> Self {
133 let mut res = Self::new(StatusCode::OK);
134 res.body = body.into();
135 res.headers
136 .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
137 res
138 }
139
140 pub fn with_body_bytes(mut self, body: impl Into<Bytes>) -> Self {
142 self.body = body.into();
143 self
144 }
145
146 pub fn with_status(mut self, status: StatusCode) -> Self {
147 self.status = status;
148 self
149 }
150
151 pub fn with_header<K, V>(mut self, name: K, value: V) -> Self
154 where
155 K: TryInto<HeaderName>,
156 V: TryInto<HeaderValue>,
157 {
158 match (name.try_into(), value.try_into()) {
159 (Ok(name), Ok(value)) => {
160 self.headers.insert(name, value);
161 }
162 _ => tracing::warn!("ignoring invalid response header"),
163 }
164 self
165 }
166
167 pub fn status(&self) -> StatusCode {
168 self.status
169 }
170
171 pub fn headers(&self) -> &HeaderMap {
172 &self.headers
173 }
174
175 pub fn headers_mut(&mut self) -> &mut HeaderMap {
176 &mut self.headers
177 }
178
179 pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
180 self.headers.get(name).and_then(|v| v.to_str().ok())
181 }
182
183 pub fn extensions(&self) -> &Extensions {
186 &self.extensions
187 }
188
189 pub fn extensions_mut(&mut self) -> &mut Extensions {
190 &mut self.extensions
191 }
192
193 pub fn body(&self) -> &Bytes {
194 &self.body
195 }
196
197 pub fn fresh_when(
207 mut self,
208 ctx: &crate::Context,
209 last_modified: chrono::DateTime<chrono::Utc>,
210 ) -> Self {
211 use sha2::Digest;
212 let modified = last_modified
213 .format("%a, %d %b %Y %H:%M:%S GMT")
214 .to_string();
215 let digest = sha2::Sha256::digest(&self.body);
216 let etag = format!(
217 "W/\"{}\"",
218 digest[..16]
219 .iter()
220 .map(|b| format!("{b:02x}"))
221 .collect::<String>()
222 );
223 let fresh = match ctx.header(header::IF_NONE_MATCH) {
224 Some(tags) => tags.split(',').any(|tag| {
225 let tag = tag.trim();
227 tag == "*" || tag.trim_start_matches("W/") == etag.trim_start_matches("W/")
228 }),
229 None => ctx
230 .header(header::IF_MODIFIED_SINCE)
231 .and_then(crate::time::parse_http_date)
232 .is_some_and(|since| since.timestamp() >= last_modified.timestamp()),
233 };
234 if let Ok(value) = HeaderValue::from_str(&modified) {
235 self.headers.insert(header::LAST_MODIFIED, value);
236 }
237 if let Ok(value) = HeaderValue::from_str(&etag) {
238 self.headers.insert(header::ETAG, value);
239 }
240 if fresh && self.status == StatusCode::OK {
241 self.status = StatusCode::NOT_MODIFIED;
242 self.body = Bytes::new();
243 self.headers.remove(header::CONTENT_TYPE);
244 }
245 self
246 }
247
248 pub fn is_head(&self) -> bool {
250 self.extensions.get::<Head>().is_some()
251 }
252
253 pub fn body_text(&self) -> String {
255 String::from_utf8_lossy(&self.body).into_owned()
256 }
257
258 pub fn body_json(&self) -> serde_json::Value {
261 serde_json::from_slice(&self.body).unwrap_or_default()
262 }
263
264 pub(crate) fn into_http(self) -> http::Response<Full<Bytes>> {
265 let mut res = http::Response::new(Full::new(self.body));
266 *res.status_mut() = self.status;
267 *res.headers_mut() = self.headers;
268 res
269 }
270}
271
272pub trait IntoResponse {
274 fn into_response(self) -> Response;
275}
276
277static ESCAPE_HTML: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
278
279pub fn escape_html_entities_in_json(on: bool) {
283 ESCAPE_HTML.store(on, std::sync::atomic::Ordering::Relaxed);
284}
285
286fn escape_html(json: &[u8]) -> Vec<u8> {
289 let text = String::from_utf8_lossy(json);
290 let mut out = String::with_capacity(text.len());
291 for c in text.chars() {
292 match c {
293 '<' => out.push_str("\\u003c"),
294 '>' => out.push_str("\\u003e"),
295 '&' => out.push_str("\\u0026"),
296 '\u{2028}' => out.push_str("\\u2028"),
297 '\u{2029}' => out.push_str("\\u2029"),
298 c => out.push(c),
299 }
300 }
301 out.into_bytes()
302}
303
304#[cfg(test)]
305mod escape_tests {
306 #[test]
307 fn escapes_as_rails_does() {
308 let json = br#"{"url":"/a?b=1&c=<x>"}"#;
309 assert_eq!(
310 String::from_utf8(super::escape_html(json)).unwrap(),
311 r#"{"url":"/a?b=1\u0026c=\u003cx\u003e"}"#
312 );
313 }
314}
315
316impl IntoResponse for Response {
317 fn into_response(self) -> Response {
318 self
319 }
320}
321
322impl IntoResponse for &'static str {
323 fn into_response(self) -> Response {
324 Response::text(self)
325 }
326}
327
328impl IntoResponse for String {
329 fn into_response(self) -> Response {
330 Response::text(self)
331 }
332}
333
334impl IntoResponse for StatusCode {
335 fn into_response(self) -> Response {
336 Response::new(self)
337 }
338}
339
340impl<R: IntoResponse> IntoResponse for (StatusCode, R) {
341 fn into_response(self) -> Response {
342 self.1.into_response().with_status(self.0)
343 }
344}
345
346impl<R: IntoResponse, E: IntoResponse> IntoResponse for Result<R, E> {
347 fn into_response(self) -> Response {
348 match self {
349 Ok(r) => r.into_response(),
350 Err(e) => e.into_response(),
351 }
352 }
353}
354
355#[derive(Debug, Clone)]
357pub struct Html<T>(pub T);
358
359impl<T: Into<String>> IntoResponse for Html<T> {
360 fn into_response(self) -> Response {
361 Response::html(self.0)
362 }
363}
364
365#[derive(Debug, Clone)]
367pub struct Json<T>(pub T);
368
369impl Json<()> {
370 pub fn object() -> crate::serialize::Object {
374 crate::serialize::Object::new()
375 }
376}
377
378impl<T: Serialize> IntoResponse for Json<T> {
379 fn into_response(self) -> Response {
380 Response::json(&self.0)
381 }
382}
383
384pub trait Returned {
389 fn returned(self) -> crate::Result;
391}
392
393#[doc(hidden)]
395pub fn returned(value: impl Returned) -> crate::Result {
396 value.returned()
397}
398
399impl<R: IntoResponse> Returned for crate::Result<R> {
400 fn returned(self) -> crate::Result {
401 self.map(IntoResponse::into_response)
402 }
403}
404
405impl Returned for crate::Error {
406 fn returned(self) -> crate::Result {
407 Err(self)
408 }
409}
410
411macro_rules! returned_as_response {
412 ($($ty:ty),* $(,)?) => {$(
413 impl Returned for $ty {
414 fn returned(self) -> crate::Result {
415 Ok(self.into_response())
416 }
417 }
418 )*};
419}
420
421returned_as_response!(
422 Response,
423 &'static str,
424 String,
425 StatusCode,
426 crate::view::Rendered
427);
428
429impl<R: IntoResponse> Returned for (StatusCode, R) {
430 fn returned(self) -> crate::Result {
431 Ok(self.into_response())
432 }
433}
434
435impl<T: Into<String>> Returned for Html<T> {
436 fn returned(self) -> crate::Result {
437 Ok(self.into_response())
438 }
439}
440
441impl<T: Serialize> Returned for Json<T> {
442 fn returned(self) -> crate::Result {
443 Ok(self.into_response())
444 }
445}
446
447#[doc(hidden)]
451pub trait RedirectOption {
452 fn apply(self, key: &str, status: &mut StatusCode);
453}
454
455macro_rules! redirect_text {
456 ($($ty:ty),*) => {$(
457 impl RedirectOption for $ty {
458 #[track_caller]
459 fn apply(self, key: &str, status: &mut StatusCode) {
460 if key == "status" {
461 *status = IntoStatus::into_status(AsRef::<str>::as_ref(&self));
462 } else {
463 crate::request::put_flash(key, AsRef::<str>::as_ref(&self));
464 }
465 }
466 }
467 )*};
468}
469redirect_text!(&str, String, &String);
470
471macro_rules! redirect_status {
472 ($($ty:ty),*) => {$(
473 impl RedirectOption for $ty {
474 #[track_caller]
475 fn apply(self, key: &str, status: &mut StatusCode) {
476 assert!(key == "status", "a flash (`{key}:`) is text");
477 *status = self.into_status();
478 }
479 }
480 )*};
481}
482redirect_status!(StatusCode, u16, i32);
483
484pub trait IntoStatus {
488 fn into_status(self) -> StatusCode;
489}
490
491impl IntoStatus for StatusCode {
492 fn into_status(self) -> StatusCode {
493 self
494 }
495}
496
497impl IntoStatus for u16 {
498 #[track_caller]
499 fn into_status(self) -> StatusCode {
500 StatusCode::from_u16(self).unwrap_or_else(|_| panic!("{self} isn't an HTTP status"))
501 }
502}
503
504impl IntoStatus for i32 {
505 #[track_caller]
506 fn into_status(self) -> StatusCode {
507 u16::try_from(self)
508 .ok()
509 .and_then(|code| StatusCode::from_u16(code).ok())
510 .unwrap_or_else(|| panic!("{self} isn't an HTTP status"))
511 }
512}
513
514impl IntoStatus for &str {
515 #[track_caller]
519 fn into_status(self) -> StatusCode {
520 status_named(self).unwrap_or_else(|| panic!("no HTTP status is called `:{self}`"))
521 }
522}
523
524pub fn status_name(status: StatusCode) -> String {
526 let reason = status.canonical_reason().unwrap_or(status.as_str());
527 reason
528 .to_ascii_lowercase()
529 .replace(['-', '\''], "")
530 .split(|c: char| !c.is_ascii_alphanumeric())
531 .filter(|word| !word.is_empty())
532 .collect::<Vec<_>>()
533 .join("_")
534}
535
536pub fn status_named(name: &str) -> Option<StatusCode> {
538 (100..600)
539 .filter_map(|code| StatusCode::from_u16(code).ok())
540 .find(|status| status_name(*status) == name)
541}