-
Notifications
You must be signed in to change notification settings - Fork 969
/
mod.rs
80 lines (72 loc) · 2.05 KB
/
mod.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
//! Types and traits for generating responses.
//!
//! See [`axum::response`] for more details.
//!
//! [`axum::response`]: https://docs.rs/axum/latest/axum/response/index.html
use crate::body::BoxBody;
mod append_headers;
mod into_response;
mod into_response_parts;
pub use self::{
append_headers::AppendHeaders,
into_response::IntoResponse,
into_response_parts::{IntoResponseParts, ResponseParts, TryIntoHeaderError},
};
/// Type alias for [`http::Response`] whose body type defaults to [`BoxBody`], the most common body
/// type used with axum.
pub type Response<T = BoxBody> = http::Response<T>;
/// A flexible [`IntoResponse`]-based result type
///
/// All types which implement [`IntoResponse`] can be converted to an [`ErrorResponse`].
/// This makes it useful as a general error type for functions which combine
/// multiple distinct error types but all of which implement [`IntoResponse`].
///
/// For example, note that the error types below differ. However, both can be
/// used with the [`Result`], and therefore the `?` operator, since they both
/// implement [`IntoResponse`].
///
/// ```no_run
/// use axum::{
/// response::{IntoResponse, Response, Result},
/// http::StatusCode,
/// };
///
/// fn foo() -> Result<(), (StatusCode, &'static str)> {
/// Err((StatusCode::NOT_FOUND, "not found"))
/// }
///
/// fn bar() -> Result<(), StatusCode> {
/// Err(StatusCode::BAD_REQUEST)
/// }
///
/// fn handler() -> Result<&'static str> {
/// foo()?;
/// bar()?;
/// Ok("ok")
/// }
/// ```
pub type Result<T, E = ErrorResponse> = std::result::Result<T, E>;
impl<T> IntoResponse for Result<T>
where
T: IntoResponse,
{
fn into_response(self) -> Response {
match self {
Ok(ok) => ok.into_response(),
Err(err) => err.0,
}
}
}
/// An [`IntoResponse`]-based error type
///
/// See [`Result`] for more details.
#[derive(Debug)]
pub struct ErrorResponse(Response);
impl<T> From<T> for ErrorResponse
where
T: IntoResponse,
{
fn from(value: T) -> Self {
Self(value.into_response())
}
}