Skip to main content

axum_core/response/
into_response_parts.rs

1use super::{IntoResponse, Response};
2use http::{
3    header::{HeaderMap, HeaderName, HeaderValue},
4    Extensions, StatusCode,
5};
6use std::{convert::Infallible, fmt};
7
8/// Trait for adding headers and extensions to a response.
9///
10/// # Example
11///
12/// ```rust
13/// use axum::{
14///     response::{ResponseParts, IntoResponse, IntoResponseParts, Response},
15///     http::{StatusCode, header::{HeaderName, HeaderValue}},
16/// };
17///
18/// // Hypothetical helper type for setting a single header
19/// struct SetHeader<'a>(&'a str, &'a str);
20///
21/// impl<'a> IntoResponseParts for SetHeader<'a> {
22///     type Error = (StatusCode, String);
23///
24///     fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
25///         match (self.0.parse::<HeaderName>(), self.1.parse::<HeaderValue>()) {
26///             (Ok(name), Ok(value)) => {
27///                 res.headers_mut().insert(name, value);
28///             },
29///             (Err(_), _) => {
30///                 return Err((
31///                     StatusCode::INTERNAL_SERVER_ERROR,
32///                     format!("Invalid header name {}", self.0),
33///                 ));
34///             },
35///             (_, Err(_)) => {
36///                 return Err((
37///                     StatusCode::INTERNAL_SERVER_ERROR,
38///                     format!("Invalid header value {}", self.1),
39///                 ));
40///             },
41///         }
42///
43///         Ok(res)
44///     }
45/// }
46///
47/// // It's also recommended to implement `IntoResponse` so `SetHeader` can be used on its own as
48/// // the response
49/// impl<'a> IntoResponse for SetHeader<'a> {
50///     fn into_response(self) -> Response {
51///         // This gives an empty response with the header
52///         (self, ()).into_response()
53///     }
54/// }
55///
56/// // We can now return `SetHeader` in responses
57/// //
58/// // Note that returning `impl IntoResponse` might be easier if the response has many parts to
59/// // it. The return type is written out here for clarity.
60/// async fn handler() -> (SetHeader<'static>, SetHeader<'static>, &'static str) {
61///     (
62///         SetHeader("server", "axum"),
63///         SetHeader("x-foo", "custom"),
64///         "body",
65///     )
66/// }
67///
68/// // Or on its own as the whole response
69/// async fn other_handler() -> SetHeader<'static> {
70///     SetHeader("x-foo", "custom")
71/// }
72/// ```
73#[diagnostic::on_unimplemented(
74    note = "See `https://docs.rs/axum/0.8/axum/response/trait.IntoResponseParts.html` for details"
75)]
76pub trait IntoResponseParts {
77    /// The type returned in the event of an error.
78    ///
79    /// This can be used to fallibly convert types into headers or extensions.
80    type Error: IntoResponse;
81
82    /// Set parts of the response
83    fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error>;
84}
85
86impl<T> IntoResponseParts for Option<T>
87where
88    T: IntoResponseParts,
89{
90    type Error = T::Error;
91
92    fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> {
93        if let Some(inner) = self {
94            inner.into_response_parts(res)
95        } else {
96            Ok(res)
97        }
98    }
99}
100
101/// Parts of a response.
102///
103/// Used with [`IntoResponseParts`].
104#[derive(Debug)]
105pub struct ResponseParts {
106    pub(crate) res: Response,
107}
108
109impl ResponseParts {
110    /// Gets the response status code.
111    #[must_use]
112    pub fn status(&self) -> StatusCode {
113        self.res.status()
114    }
115
116    /// Gets a mutable reference to the response status code.
117    #[must_use]
118    pub fn status_mut(&mut self) -> &mut StatusCode {
119        self.res.status_mut()
120    }
121
122    /// Gets a reference to the response headers.
123    #[must_use]
124    pub fn headers(&self) -> &HeaderMap {
125        self.res.headers()
126    }
127
128    /// Gets a mutable reference to the response headers.
129    #[must_use]
130    pub fn headers_mut(&mut self) -> &mut HeaderMap {
131        self.res.headers_mut()
132    }
133
134    /// Gets a reference to the response extensions.
135    #[must_use]
136    pub fn extensions(&self) -> &Extensions {
137        self.res.extensions()
138    }
139
140    /// Gets a mutable reference to the response extensions.
141    #[must_use]
142    pub fn extensions_mut(&mut self) -> &mut Extensions {
143        self.res.extensions_mut()
144    }
145}
146
147impl IntoResponseParts for HeaderMap {
148    type Error = Infallible;
149
150    fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
151        res.headers_mut().extend(self);
152        Ok(res)
153    }
154}
155
156impl<K, V, const N: usize> IntoResponseParts for [(K, V); N]
157where
158    K: TryInto<HeaderName>,
159    K::Error: fmt::Display,
160    V: TryInto<HeaderValue>,
161    V::Error: fmt::Display,
162{
163    type Error = TryIntoHeaderError<K::Error, V::Error>;
164
165    fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
166        for (key, value) in self {
167            let key = key.try_into().map_err(TryIntoHeaderError::key)?;
168            let value = value.try_into().map_err(TryIntoHeaderError::value)?;
169            res.headers_mut().insert(key, value);
170        }
171
172        Ok(res)
173    }
174}
175
176/// Error returned if converting a value to a header fails.
177#[derive(Debug)]
178pub struct TryIntoHeaderError<K, V> {
179    kind: TryIntoHeaderErrorKind<K, V>,
180}
181
182impl<K, V> TryIntoHeaderError<K, V> {
183    pub(super) fn key(err: K) -> Self {
184        Self {
185            kind: TryIntoHeaderErrorKind::Key(err),
186        }
187    }
188
189    pub(super) fn value(err: V) -> Self {
190        Self {
191            kind: TryIntoHeaderErrorKind::Value(err),
192        }
193    }
194}
195
196#[derive(Debug)]
197enum TryIntoHeaderErrorKind<K, V> {
198    Key(K),
199    Value(V),
200}
201
202impl<K, V> IntoResponse for TryIntoHeaderError<K, V>
203where
204    K: fmt::Display,
205    V: fmt::Display,
206{
207    fn into_response(self) -> Response {
208        match self.kind {
209            TryIntoHeaderErrorKind::Key(inner) => {
210                (StatusCode::INTERNAL_SERVER_ERROR, inner.to_string()).into_response()
211            }
212            TryIntoHeaderErrorKind::Value(inner) => {
213                (StatusCode::INTERNAL_SERVER_ERROR, inner.to_string()).into_response()
214            }
215        }
216    }
217}
218
219impl<K, V> fmt::Display for TryIntoHeaderError<K, V> {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        match self.kind {
222            TryIntoHeaderErrorKind::Key(_) => write!(f, "failed to convert key to a header name"),
223            TryIntoHeaderErrorKind::Value(_) => {
224                write!(f, "failed to convert value to a header value")
225            }
226        }
227    }
228}
229
230impl<K, V> std::error::Error for TryIntoHeaderError<K, V>
231where
232    K: std::error::Error + 'static,
233    V: std::error::Error + 'static,
234{
235    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
236        match &self.kind {
237            TryIntoHeaderErrorKind::Key(inner) => Some(inner),
238            TryIntoHeaderErrorKind::Value(inner) => Some(inner),
239        }
240    }
241}
242
243macro_rules! impl_into_response_parts {
244    ( $($ty:ident),* $(,)? ) => {
245        #[allow(non_snake_case)]
246        impl<$($ty,)*> IntoResponseParts for ($($ty,)*)
247        where
248            $( $ty: IntoResponseParts, )*
249        {
250            type Error = Response;
251
252            fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> {
253                let ($($ty,)*) = self;
254
255                $(
256                    let res = match $ty.into_response_parts(res) {
257                        Ok(res) => res,
258                        Err(err) => {
259                            let mut err_res = err.into_response();
260                            err_res.extensions_mut().insert(super::IntoResponseFailed);
261                            return Err(err_res);
262                        }
263                    };
264                )*
265
266                Ok(res)
267            }
268        }
269    }
270}
271
272all_the_tuples_no_last_special_case!(impl_into_response_parts);
273
274impl IntoResponseParts for Extensions {
275    type Error = Infallible;
276
277    fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
278        res.extensions_mut().extend(self);
279        Ok(res)
280    }
281}
282
283impl IntoResponseParts for () {
284    type Error = Infallible;
285
286    fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> {
287        Ok(res)
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use http::StatusCode;
294
295    use crate::response::IntoResponse;
296
297    #[test]
298    fn failed_into_response_parts() {
299        let response = (StatusCode::CREATED, [("\n", "\n")]).into_response();
300        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
301
302        let response = (StatusCode::CREATED, [("\n", "\n")], ()).into_response();
303        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
304    }
305}