Skip to main content

axum_core/response/
into_response.rs

1use super::{ForceStatusCode, IntoResponseFailed, IntoResponseParts, Response, ResponseParts};
2use crate::{body::Body, BoxError};
3use bytes::{buf::Chain, Buf, Bytes, BytesMut};
4use http::{
5    header::{self, HeaderMap, HeaderName, HeaderValue},
6    Extensions, StatusCode,
7};
8use http_body::{Frame, SizeHint};
9use std::{
10    borrow::Cow,
11    convert::Infallible,
12    fmt,
13    pin::Pin,
14    task::{Context, Poll},
15};
16
17/// Trait for generating responses.
18///
19/// Types that implement `IntoResponse` can be returned from handlers.
20///
21/// # Implementing `IntoResponse`
22///
23/// You generally shouldn't have to implement `IntoResponse` manually, as axum
24/// provides implementations for many common types.
25///
26/// However it might be necessary if you have a custom error type that you want
27/// to return from handlers:
28///
29/// ```rust
30/// use axum::{
31///     Router,
32///     body::{self, Bytes},
33///     routing::get,
34///     http::StatusCode,
35///     response::{IntoResponse, Response},
36/// };
37///
38/// enum MyError {
39///     SomethingWentWrong,
40///     SomethingElseWentWrong,
41/// }
42///
43/// impl IntoResponse for MyError {
44///     fn into_response(self) -> Response {
45///         let body = match self {
46///             MyError::SomethingWentWrong => "something went wrong",
47///             MyError::SomethingElseWentWrong => "something else went wrong",
48///         };
49///
50///         // it's often easiest to implement `IntoResponse` by calling other implementations
51///         (StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
52///     }
53/// }
54///
55/// // `Result<impl IntoResponse, MyError>` can now be returned from handlers
56/// let app = Router::new().route("/", get(handler));
57///
58/// async fn handler() -> Result<(), MyError> {
59///     Err(MyError::SomethingWentWrong)
60/// }
61/// # let _: Router = app;
62/// ```
63///
64/// Or if you have a custom body type you'll also need to implement
65/// `IntoResponse` for it:
66///
67/// ```rust
68/// use axum::{
69///     body,
70///     routing::get,
71///     response::{IntoResponse, Response},
72///     body::Body,
73///     Router,
74/// };
75/// use http::HeaderMap;
76/// use bytes::Bytes;
77/// use http_body::Frame;
78/// use std::{
79///     convert::Infallible,
80///     task::{Poll, Context},
81///     pin::Pin,
82/// };
83///
84/// struct MyBody;
85///
86/// // First implement `Body` for `MyBody`. This could for example use
87/// // some custom streaming protocol.
88/// impl http_body::Body for MyBody {
89///     type Data = Bytes;
90///     type Error = Infallible;
91///
92///     fn poll_frame(
93///         self: Pin<&mut Self>,
94///         cx: &mut Context<'_>,
95///     ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
96///         # unimplemented!()
97///         // ...
98///     }
99/// }
100///
101/// // Now we can implement `IntoResponse` directly for `MyBody`
102/// impl IntoResponse for MyBody {
103///     fn into_response(self) -> Response {
104///         Response::new(Body::new(self))
105///     }
106/// }
107///
108/// // `MyBody` can now be returned from handlers.
109/// let app = Router::new().route("/", get(|| async { MyBody }));
110/// # let _: Router = app;
111/// ```
112#[diagnostic::on_unimplemented(
113    note = "See `https://docs.rs/axum/0.8/axum/response/trait.IntoResponse.html` for details"
114)]
115pub trait IntoResponse {
116    /// Create a response.
117    #[must_use]
118    fn into_response(self) -> Response;
119}
120
121impl IntoResponse for StatusCode {
122    fn into_response(self) -> Response {
123        let mut res = ().into_response();
124        *res.status_mut() = self;
125        res
126    }
127}
128
129impl IntoResponse for () {
130    fn into_response(self) -> Response {
131        Body::unknown().into_response()
132    }
133}
134
135impl IntoResponse for Infallible {
136    fn into_response(self) -> Response {
137        match self {}
138    }
139}
140
141impl<T, E> IntoResponse for Result<T, E>
142where
143    T: IntoResponse,
144    E: IntoResponse,
145{
146    fn into_response(self) -> Response {
147        match self {
148            Ok(value) => value.into_response(),
149            Err(err) => err.into_response(),
150        }
151    }
152}
153
154impl<B> IntoResponse for Response<B>
155where
156    B: http_body::Body<Data = Bytes> + Send + 'static,
157    B::Error: Into<BoxError>,
158{
159    fn into_response(self) -> Response {
160        self.map(Body::new)
161    }
162}
163
164impl IntoResponse for http::response::Parts {
165    fn into_response(self) -> Response {
166        Response::from_parts(self, Body::empty())
167    }
168}
169
170impl IntoResponse for Body {
171    fn into_response(self) -> Response {
172        Response::new(self)
173    }
174}
175
176impl IntoResponse for &'static str {
177    fn into_response(self) -> Response {
178        Cow::Borrowed(self).into_response()
179    }
180}
181
182impl IntoResponse for String {
183    fn into_response(self) -> Response {
184        Cow::<'static, str>::Owned(self).into_response()
185    }
186}
187
188impl IntoResponse for Box<str> {
189    fn into_response(self) -> Response {
190        String::from(self).into_response()
191    }
192}
193
194impl IntoResponse for Cow<'static, str> {
195    fn into_response(self) -> Response {
196        let mut res = Body::from(self).into_response();
197        res.headers_mut().insert(
198            header::CONTENT_TYPE,
199            HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),
200        );
201        res
202    }
203}
204
205impl IntoResponse for Bytes {
206    fn into_response(self) -> Response {
207        let mut res = Body::from(self).into_response();
208        res.headers_mut().insert(
209            header::CONTENT_TYPE,
210            HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()),
211        );
212        res
213    }
214}
215
216impl IntoResponse for BytesMut {
217    fn into_response(self) -> Response {
218        self.freeze().into_response()
219    }
220}
221
222impl<T, U> IntoResponse for Chain<T, U>
223where
224    T: Buf + Unpin + Send + 'static,
225    U: Buf + Unpin + Send + 'static,
226{
227    fn into_response(self) -> Response {
228        let (first, second) = self.into_inner();
229        let mut res = Response::new(Body::new(BytesChainBody {
230            first: Some(first),
231            second: Some(second),
232        }));
233        res.headers_mut().insert(
234            header::CONTENT_TYPE,
235            HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()),
236        );
237        res
238    }
239}
240
241struct BytesChainBody<T, U> {
242    first: Option<T>,
243    second: Option<U>,
244}
245
246impl<T, U> http_body::Body for BytesChainBody<T, U>
247where
248    T: Buf + Unpin,
249    U: Buf + Unpin,
250{
251    type Data = Bytes;
252    type Error = Infallible;
253
254    fn poll_frame(
255        mut self: Pin<&mut Self>,
256        _cx: &mut Context<'_>,
257    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
258        if let Some(mut buf) = self.first.take() {
259            let bytes = buf.copy_to_bytes(buf.remaining());
260            return Poll::Ready(Some(Ok(Frame::data(bytes))));
261        }
262
263        if let Some(mut buf) = self.second.take() {
264            let bytes = buf.copy_to_bytes(buf.remaining());
265            return Poll::Ready(Some(Ok(Frame::data(bytes))));
266        }
267
268        Poll::Ready(None)
269    }
270
271    fn is_end_stream(&self) -> bool {
272        self.first.is_none() && self.second.is_none()
273    }
274
275    fn size_hint(&self) -> SizeHint {
276        match (self.first.as_ref(), self.second.as_ref()) {
277            (Some(first), Some(second)) => {
278                let total_size = first.remaining() + second.remaining();
279                SizeHint::with_exact(total_size as u64)
280            }
281            (Some(buf), None) => SizeHint::with_exact(buf.remaining() as u64),
282            (None, Some(buf)) => SizeHint::with_exact(buf.remaining() as u64),
283            (None, None) => SizeHint::with_exact(0),
284        }
285    }
286}
287
288impl IntoResponse for &'static [u8] {
289    fn into_response(self) -> Response {
290        Cow::Borrowed(self).into_response()
291    }
292}
293
294impl<const N: usize> IntoResponse for &'static [u8; N] {
295    fn into_response(self) -> Response {
296        self.as_slice().into_response()
297    }
298}
299
300impl<const N: usize> IntoResponse for [u8; N] {
301    fn into_response(self) -> Response {
302        self.to_vec().into_response()
303    }
304}
305
306impl IntoResponse for Vec<u8> {
307    fn into_response(self) -> Response {
308        Cow::<'static, [u8]>::Owned(self).into_response()
309    }
310}
311
312impl IntoResponse for Box<[u8]> {
313    fn into_response(self) -> Response {
314        Vec::from(self).into_response()
315    }
316}
317
318impl IntoResponse for Cow<'static, [u8]> {
319    fn into_response(self) -> Response {
320        let mut res = Body::from(self).into_response();
321        res.headers_mut().insert(
322            header::CONTENT_TYPE,
323            HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()),
324        );
325        res
326    }
327}
328
329impl<R> IntoResponse for (StatusCode, R)
330where
331    R: IntoResponse,
332{
333    fn into_response(self) -> Response {
334        let mut res = self.1.into_response();
335        if res.extensions().get::<IntoResponseFailed>().is_none() {
336            *res.status_mut() = self.0;
337        }
338        res
339    }
340}
341
342impl IntoResponse for HeaderMap {
343    fn into_response(self) -> Response {
344        let mut res = ().into_response();
345        *res.headers_mut() = self;
346        res
347    }
348}
349
350impl IntoResponse for Extensions {
351    fn into_response(self) -> Response {
352        let mut res = ().into_response();
353        *res.extensions_mut() = self;
354        res
355    }
356}
357
358impl<K, V, const N: usize> IntoResponse for [(K, V); N]
359where
360    K: TryInto<HeaderName>,
361    K::Error: fmt::Display,
362    V: TryInto<HeaderValue>,
363    V::Error: fmt::Display,
364{
365    fn into_response(self) -> Response {
366        (self, ()).into_response()
367    }
368}
369
370impl<R> IntoResponse for (http::response::Parts, R)
371where
372    R: IntoResponse,
373{
374    fn into_response(self) -> Response {
375        let (parts, res) = self;
376        (parts.status, parts.headers, parts.extensions, res).into_response()
377    }
378}
379
380impl<R> IntoResponse for (http::response::Response<()>, R)
381where
382    R: IntoResponse,
383{
384    fn into_response(self) -> Response {
385        let (template, res) = self;
386        let (parts, ()) = template.into_parts();
387        (parts, res).into_response()
388    }
389}
390
391impl<R> IntoResponse for (R,)
392where
393    R: IntoResponse,
394{
395    fn into_response(self) -> Response {
396        let (res,) = self;
397        res.into_response()
398    }
399}
400
401macro_rules! impl_into_response {
402    ( $($ty:ident),* $(,)? ) => {
403        #[allow(non_snake_case)]
404        impl<R, $($ty,)*> IntoResponse for ($($ty),*, R)
405        where
406            $( $ty: IntoResponseParts, )*
407            R: IntoResponse,
408        {
409            fn into_response(self) -> Response {
410                let ($($ty),*, res) = self;
411
412                let res = res.into_response();
413                if res.extensions().get::<IntoResponseFailed>().is_none() {
414                    let parts = ResponseParts { res };
415                    let parts = match ($($ty,)*).into_response_parts(parts) {
416                        Ok(parts) => parts,
417                        Err(err) => return err.into_response(),
418                    };
419                    parts.res
420                } else {
421                    res
422                }
423            }
424        }
425
426        #[allow(non_snake_case)]
427        impl<R, $($ty,)*> IntoResponse for (StatusCode, $($ty),*, R)
428        where
429            $( $ty: IntoResponseParts, )*
430            R: IntoResponse,
431        {
432            fn into_response(self) -> Response {
433                let (status, $($ty),*, res) = self;
434
435                let res = res.into_response();
436                if res.extensions().get::<IntoResponseFailed>().is_none() {
437                    let parts = ResponseParts { res };
438                    let mut parts = match ($($ty,)*).into_response_parts(parts) {
439                        Ok(parts) => parts,
440                        Err(err) => return err.into_response(),
441                    };
442
443                    // Don't call `(status, parts.res).into_response()` since that checks for
444                    // `IntoResponseFailed` and skips setting the status. We've already done that
445                    // check here so overriding the status is required if returning
446                    // `(IntoResponseFailed, StatusCode::INTERNAL_SERVER_ERROR)`
447                    *parts.res.status_mut() = status;
448                    parts.res
449                } else {
450                    res
451                }
452            }
453        }
454
455        #[allow(non_snake_case)]
456        impl<R, $($ty,)*> IntoResponse for (ForceStatusCode, $($ty),*, R)
457        where
458            $( $ty: IntoResponseParts, )*
459            R: IntoResponse,
460        {
461            fn into_response(self) -> Response {
462                let (status, $($ty),*, res) = self;
463
464                let res = res.into_response();
465                let parts = ResponseParts { res };
466                let parts = match ($($ty,)*).into_response_parts(parts) {
467                    Ok(parts) => parts,
468                    Err(err) => return err.into_response(),
469                };
470
471                (status, parts.res).into_response()
472            }
473        }
474
475        #[allow(non_snake_case)]
476        impl<R, $($ty,)*> IntoResponse for (http::response::Parts, $($ty),*, R)
477        where
478            $( $ty: IntoResponseParts, )*
479            R: IntoResponse,
480        {
481            fn into_response(self) -> Response {
482                let (outer_parts, $($ty),*, res) = self;
483
484                let res = res.into_response();
485                if res.extensions().get::<IntoResponseFailed>().is_none() {
486                    let parts = ResponseParts { res };
487                    let mut parts = match ($($ty,)*).into_response_parts(parts) {
488                        Ok(parts) => parts,
489                        Err(err) => return err.into_response(),
490                    };
491
492                    // Don't call `(outer_parts, parts.res).into_response()` for the same reason we
493                    // don't call `(status, parts.res).into_response()` in the above impl.
494                    *parts.res.status_mut() = outer_parts.status;
495                    parts.res.headers_mut().extend(outer_parts.headers);
496                    parts.res.extensions_mut().extend(outer_parts.extensions);
497                    parts.res
498                } else {
499                    res
500                }
501            }
502        }
503
504        #[allow(non_snake_case)]
505        impl<R, $($ty,)*> IntoResponse for (http::response::Response<()>, $($ty),*, R)
506        where
507            $( $ty: IntoResponseParts, )*
508            R: IntoResponse,
509        {
510            fn into_response(self) -> Response {
511                let (template, $($ty),*, res) = self;
512                let (parts, ()) = template.into_parts();
513                (parts, $($ty),*, res).into_response()
514            }
515        }
516    }
517}
518
519all_the_tuples_no_last_special_case!(impl_into_response);