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