Skip to main content

axum/response/
mod.rs

1#![doc = include_str!("../docs/response.md")]
2
3use http::{header, HeaderValue, StatusCode};
4
5mod redirect;
6
7pub mod sse;
8
9#[doc(no_inline)]
10#[cfg(feature = "json")]
11pub use crate::Json;
12
13#[cfg(feature = "form")]
14#[doc(no_inline)]
15pub use crate::form::Form;
16
17#[doc(no_inline)]
18pub use crate::Extension;
19
20#[doc(inline)]
21pub use axum_core::response::{
22    AppendHeaders, ErrorResponse, IntoResponse, IntoResponseFailed, IntoResponseParts, Response,
23    ResponseParts, Result,
24};
25
26#[doc(inline)]
27pub use self::redirect::Redirect;
28
29#[doc(inline)]
30pub use sse::Sse;
31
32/// An HTML response.
33///
34/// Will automatically get `Content-Type: text/html`.
35#[derive(Clone, Copy, Debug)]
36#[must_use]
37pub struct Html<T>(pub T);
38
39impl<T> IntoResponse for Html<T>
40where
41    T: IntoResponse,
42{
43    fn into_response(self) -> Response {
44        (
45            [(
46                header::CONTENT_TYPE,
47                HeaderValue::from_static(mime::TEXT_HTML_UTF_8.as_ref()),
48            )],
49            self.0,
50        )
51            .into_response()
52    }
53}
54
55impl<T> From<T> for Html<T> {
56    fn from(inner: T) -> Self {
57        Self(inner)
58    }
59}
60
61/// An empty response with 204 No Content status.
62///
63/// Due to historical and implementation reasons, the `IntoResponse` implementation of `()`
64/// (unit type) returns an empty response with 200 [`StatusCode::OK`] status.
65/// If you specifically want a 204 [`StatusCode::NO_CONTENT`] status, you can use either `StatusCode` type
66/// directly, or this shortcut struct for self-documentation.
67///
68/// ```
69/// use axum::{extract::Path, response::NoContent};
70///
71/// async fn delete_user(Path(user): Path<String>) -> Result<NoContent, String> {
72///     // ...access database...
73/// # drop(user);
74///     Ok(NoContent)
75/// }
76/// ```
77#[derive(Debug, Clone, Copy)]
78pub struct NoContent;
79
80impl IntoResponse for NoContent {
81    fn into_response(self) -> Response {
82        StatusCode::NO_CONTENT.into_response()
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use crate::extract::Extension;
89    use crate::test_helpers::*;
90    use crate::Json;
91    use crate::{routing::get, Router};
92    use axum_core::response::ForceStatusCode;
93    use axum_core::response::{
94        IntoResponse, IntoResponseFailed, IntoResponseParts, Response, ResponseParts,
95    };
96    use http::HeaderMap;
97    use http::{StatusCode, Uri};
98    use std::collections::HashMap;
99
100    // just needs to compile
101    #[allow(dead_code)]
102    fn impl_trait_result_works() {
103        async fn impl_trait_ok() -> Result<impl IntoResponse, ()> {
104            Ok(())
105        }
106
107        async fn impl_trait_err() -> Result<(), impl IntoResponse> {
108            Err(())
109        }
110
111        async fn impl_trait_both(uri: Uri) -> Result<impl IntoResponse, impl IntoResponse> {
112            if uri.path() == "/" {
113                Ok(())
114            } else {
115                Err(())
116            }
117        }
118
119        async fn impl_trait(uri: Uri) -> impl IntoResponse {
120            if uri.path() == "/" {
121                Ok(())
122            } else {
123                Err(())
124            }
125        }
126
127        _ = Router::<()>::new()
128            .route("/", get(impl_trait_ok))
129            .route("/", get(impl_trait_err))
130            .route("/", get(impl_trait_both))
131            .route("/", get(impl_trait));
132    }
133
134    // just needs to compile
135    #[allow(dead_code)]
136    fn tuple_responses() {
137        async fn status() -> impl IntoResponse {
138            StatusCode::OK
139        }
140
141        async fn status_headermap() -> impl IntoResponse {
142            (StatusCode::OK, HeaderMap::new())
143        }
144
145        async fn status_header_array() -> impl IntoResponse {
146            (StatusCode::OK, [("content-type", "text/plain")])
147        }
148
149        async fn status_headermap_body() -> impl IntoResponse {
150            (StatusCode::OK, HeaderMap::new(), String::new())
151        }
152
153        async fn status_header_array_body() -> impl IntoResponse {
154            (
155                StatusCode::OK,
156                [("content-type", "text/plain")],
157                String::new(),
158            )
159        }
160
161        async fn status_headermap_impl_into_response() -> impl IntoResponse {
162            (StatusCode::OK, HeaderMap::new(), impl_into_response())
163        }
164
165        async fn status_header_array_impl_into_response() -> impl IntoResponse {
166            (
167                StatusCode::OK,
168                [("content-type", "text/plain")],
169                impl_into_response(),
170            )
171        }
172
173        fn impl_into_response() -> impl IntoResponse {}
174
175        async fn status_header_array_extension_body() -> impl IntoResponse {
176            (
177                StatusCode::OK,
178                [("content-type", "text/plain")],
179                Extension(1),
180                String::new(),
181            )
182        }
183
184        async fn status_header_array_extension_mixed_body() -> impl IntoResponse {
185            (
186                StatusCode::OK,
187                [("content-type", "text/plain")],
188                Extension(1),
189                HeaderMap::new(),
190                String::new(),
191            )
192        }
193
194        //
195
196        async fn headermap() -> impl IntoResponse {
197            HeaderMap::new()
198        }
199
200        async fn header_array() -> impl IntoResponse {
201            [("content-type", "text/plain")]
202        }
203
204        async fn headermap_body() -> impl IntoResponse {
205            (HeaderMap::new(), String::new())
206        }
207
208        async fn header_array_body() -> impl IntoResponse {
209            ([("content-type", "text/plain")], String::new())
210        }
211
212        async fn headermap_impl_into_response() -> impl IntoResponse {
213            (HeaderMap::new(), impl_into_response())
214        }
215
216        async fn header_array_impl_into_response() -> impl IntoResponse {
217            ([("content-type", "text/plain")], impl_into_response())
218        }
219
220        async fn header_array_extension_body() -> impl IntoResponse {
221            (
222                [("content-type", "text/plain")],
223                Extension(1),
224                String::new(),
225            )
226        }
227
228        async fn header_array_extension_mixed_body() -> impl IntoResponse {
229            (
230                [("content-type", "text/plain")],
231                Extension(1),
232                HeaderMap::new(),
233                String::new(),
234            )
235        }
236
237        _ = Router::<()>::new()
238            .route("/", get(status))
239            .route("/", get(status_headermap))
240            .route("/", get(status_header_array))
241            .route("/", get(status_headermap_body))
242            .route("/", get(status_header_array_body))
243            .route("/", get(status_headermap_impl_into_response))
244            .route("/", get(status_header_array_impl_into_response))
245            .route("/", get(status_header_array_extension_body))
246            .route("/", get(status_header_array_extension_mixed_body))
247            .route("/", get(headermap))
248            .route("/", get(header_array))
249            .route("/", get(headermap_body))
250            .route("/", get(header_array_body))
251            .route("/", get(headermap_impl_into_response))
252            .route("/", get(header_array_impl_into_response))
253            .route("/", get(header_array_extension_body))
254            .route("/", get(header_array_extension_mixed_body));
255    }
256
257    #[test]
258    fn status_code_tuple_doesnt_override_error() {
259        // sanity check where there is just one status code
260        assert_eq!(
261            StatusCode::INTERNAL_SERVER_ERROR.into_response().status(),
262            StatusCode::INTERNAL_SERVER_ERROR
263        );
264        assert_eq!(
265            (StatusCode::INTERNAL_SERVER_ERROR,)
266                .into_response()
267                .status(),
268            StatusCode::INTERNAL_SERVER_ERROR
269        );
270
271        // non-5xx status should be changed
272        assert_eq!(
273            (StatusCode::SEE_OTHER, StatusCode::NO_CONTENT)
274                .into_response()
275                .status(),
276            StatusCode::SEE_OTHER
277        );
278        let res = (
279            StatusCode::SEE_OTHER,
280            [("location", "foo")],
281            StatusCode::NO_CONTENT,
282        )
283            .into_response();
284        assert_eq!(res.status(), StatusCode::SEE_OTHER);
285        assert_eq!(res.headers()["location"], "foo");
286
287        // 5xx status codes are also changed
288        assert_eq!(
289            (StatusCode::SEE_OTHER, StatusCode::INTERNAL_SERVER_ERROR)
290                .into_response()
291                .status(),
292            StatusCode::SEE_OTHER
293        );
294        let res = (
295            StatusCode::SEE_OTHER,
296            [("location", "foo")],
297            StatusCode::INTERNAL_SERVER_ERROR,
298        )
299            .into_response();
300        assert_eq!(res.status(), StatusCode::SEE_OTHER);
301        assert_eq!(res.headers()["location"], "foo");
302
303        // the status is not changed if `IntoResponseFailed` is used
304        assert_eq!(
305            (
306                StatusCode::SEE_OTHER,
307                (IntoResponseFailed, StatusCode::INTERNAL_SERVER_ERROR)
308            )
309                .into_response()
310                .status(),
311            StatusCode::INTERNAL_SERVER_ERROR
312        );
313        let res = (
314            StatusCode::SEE_OTHER,
315            [("location", "foo")],
316            (IntoResponseFailed, StatusCode::INTERNAL_SERVER_ERROR),
317        )
318            .into_response();
319        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
320        assert!(res.headers().get("location").is_none());
321
322        // response parts from the inner response do run
323        let res = (
324            // with status override
325            StatusCode::SEE_OTHER,
326            [("location", "foo")],
327            (
328                [("x-bar", "bar")],
329                IntoResponseFailed,
330                [("x-foo", "foo")],
331                StatusCode::INTERNAL_SERVER_ERROR,
332            ),
333        )
334            .into_response();
335        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
336        assert!(res.headers().get("location").is_none());
337        assert_eq!(res.headers()["x-foo"], "foo");
338        assert_eq!(res.headers()["x-bar"], "bar");
339
340        let res = (
341            // without status override
342            [("location", "foo")],
343            (
344                [("x-bar", "bar")],
345                IntoResponseFailed,
346                [("x-foo", "foo")],
347                StatusCode::INTERNAL_SERVER_ERROR,
348            ),
349        )
350            .into_response();
351        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
352        assert!(res.headers().get("location").is_none());
353        assert_eq!(res.headers()["x-foo"], "foo");
354        assert_eq!(res.headers()["x-bar"], "bar");
355
356        // (Parts, ...)
357        let res = (
358            Response::new(()).into_parts().0,
359            [("location", "foo")],
360            (
361                [("x-bar", "bar")],
362                IntoResponseFailed,
363                [("x-foo", "foo")],
364                StatusCode::INTERNAL_SERVER_ERROR,
365            ),
366        )
367            .into_response();
368        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
369        assert!(res.headers().get("location").is_none());
370        assert_eq!(res.headers()["x-foo"], "foo");
371        assert_eq!(res.headers()["x-bar"], "bar");
372
373        // (Response<()>, ...)
374        let res = (
375            Response::new(()),
376            [("location", "foo")],
377            (
378                [("x-bar", "bar")],
379                IntoResponseFailed,
380                [("x-foo", "foo")],
381                StatusCode::INTERNAL_SERVER_ERROR,
382            ),
383        )
384            .into_response();
385        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
386        assert!(res.headers().get("location").is_none());
387        assert_eq!(res.headers()["x-foo"], "foo");
388        assert_eq!(res.headers()["x-bar"], "bar");
389    }
390
391    #[test]
392    fn into_response_parts_failing_sets_extension() {
393        struct Fail;
394
395        impl IntoResponseParts for Fail {
396            type Error = ();
397
398            fn into_response_parts(
399                self,
400                _res: ResponseParts,
401            ) -> Result<ResponseParts, Self::Error> {
402                Err(())
403            }
404        }
405
406        impl IntoResponse for Fail {
407            fn into_response(self) -> Response {
408                (self, ()).into_response()
409            }
410        }
411
412        assert!(Fail
413            .into_response()
414            .extensions()
415            .get::<IntoResponseFailed>()
416            .is_some());
417
418        assert!((StatusCode::INTERNAL_SERVER_ERROR, Fail, ())
419            .into_response()
420            .extensions()
421            .get::<IntoResponseFailed>()
422            .is_some());
423
424        assert!((Response::new(()).into_parts().0, Fail, ())
425            .into_response()
426            .extensions()
427            .get::<IntoResponseFailed>()
428            .is_some());
429
430        assert!((Response::new(()), Fail, ())
431            .into_response()
432            .extensions()
433            .get::<IntoResponseFailed>()
434            .is_some());
435    }
436
437    #[test]
438    fn doenst_override_status_code_when_using_into_response_failed_at_same_level() {
439        assert_eq!(
440            (StatusCode::INTERNAL_SERVER_ERROR, IntoResponseFailed, ())
441                .into_response()
442                .status(),
443            StatusCode::INTERNAL_SERVER_ERROR,
444        );
445
446        #[derive(Clone)]
447        struct Thing;
448
449        let res = (
450            Response::builder()
451                .status(StatusCode::INTERNAL_SERVER_ERROR)
452                .header("x-foo", "foo")
453                .extension(Thing)
454                .body(())
455                .unwrap()
456                .into_parts()
457                .0,
458            IntoResponseFailed,
459            (),
460        )
461            .into_response();
462        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
463        assert_eq!(res.headers()["x-foo"], "foo");
464        assert!(res.extensions().get::<Thing>().is_some());
465
466        // just a sanity check
467        assert_eq!(
468            (IntoResponseFailed, ()).into_response().status(),
469            StatusCode::OK,
470        );
471    }
472
473    #[test]
474    fn force_overriding_status_code() {
475        assert_eq!(
476            ForceStatusCode(StatusCode::IM_A_TEAPOT)
477                .into_response()
478                .status(),
479            StatusCode::IM_A_TEAPOT
480        );
481
482        assert_eq!(
483            (ForceStatusCode(StatusCode::IM_A_TEAPOT),)
484                .into_response()
485                .status(),
486            StatusCode::IM_A_TEAPOT
487        );
488
489        assert_eq!(
490            (ForceStatusCode(StatusCode::IM_A_TEAPOT), ())
491                .into_response()
492                .status(),
493            StatusCode::IM_A_TEAPOT
494        );
495
496        assert_eq!(
497            (
498                ForceStatusCode(StatusCode::IM_A_TEAPOT),
499                IntoResponseFailed,
500                StatusCode::INTERNAL_SERVER_ERROR,
501            )
502                .into_response()
503                .status(),
504            StatusCode::IM_A_TEAPOT
505        );
506    }
507
508    #[crate::test]
509    async fn status_code_tuple_doesnt_override_error_json() {
510        let app = Router::new()
511            .route(
512                "/",
513                get(|| async {
514                    let not_json_compatible = HashMap::from([(Vec::from([1, 2, 3]), 123)]);
515                    (StatusCode::IM_A_TEAPOT, Json(not_json_compatible))
516                }),
517            )
518            .route(
519                "/two",
520                get(|| async {
521                    let not_json_compatible = HashMap::from([(Vec::from([1, 2, 3]), 123)]);
522                    (
523                        ForceStatusCode(StatusCode::IM_A_TEAPOT),
524                        Json(not_json_compatible),
525                    )
526                }),
527            );
528
529        let client = TestClient::new(app);
530
531        let res = client.get("/").await;
532        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
533
534        let res = client.get("/two").await;
535        assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);
536    }
537
538    #[test]
539    fn no_content() {
540        assert_eq!(
541            super::NoContent.into_response().status(),
542            StatusCode::NO_CONTENT,
543        )
544    }
545}