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
//! Axum response types for [`ProblemDetails`].
//!
//! Requires feature `axum`.
//!
//! With the `axum` feature enabled, [`ProblemDetails`] implements [`IntoResponse`] using
//! [`JsonProblemDetails`]. You can also return [`JsonProblemDetails`] to be specific.
//! If you want to return XML, you can use [`XmlProblemDetails`].
//!
//! # Example
//!
//! ```rust
//! use axum::{routing::get, Router};
//! use http::StatusCode;
//! use problem_details::ProblemDetails;
//!
//! async fn handler() -> Result<&'static str, ProblemDetails> {
//!     // always return a problem description
//!     Err(ProblemDetails::from_status_code(StatusCode::IM_A_TEAPOT)
//!         .with_detail("short and stout"))
//! }
//!
//! fn main() {
//!     let app = Router::new().route("/", get(handler));
//!     # let _app: Router = app;
//!     // build and run server...
//! }
//! ```
use axum::{
    response::{IntoResponse, Response},
    Json,
};
use http::{header, StatusCode};

use crate::ProblemDetails;

#[cfg(feature = "json")]
use crate::JsonProblemDetails;

#[cfg(feature = "xml")]
use crate::XmlProblemDetails;

#[cfg(feature = "json")]
impl<Ext> IntoResponse for JsonProblemDetails<Ext>
where
    Ext: serde::Serialize,
{
    fn into_response(self) -> Response {
        let status_code = self.0.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        let content_type = [(header::CONTENT_TYPE, Self::CONTENT_TYPE)];
        let content = Json(self.0);

        (status_code, content_type, content).into_response()
    }
}

#[cfg(feature = "xml")]
impl<Ext> IntoResponse for XmlProblemDetails<Ext>
where
    Ext: serde::Serialize,
{
    fn into_response(self) -> Response {
        let status_code = self.0.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        let content_type = [(header::CONTENT_TYPE, Self::CONTENT_TYPE)];
        let content = match self.to_body_string() {
            Ok(xml) => xml,
            Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
        };

        (status_code, content_type, content).into_response()
    }
}

#[cfg(feature = "json")]
impl<Ext> IntoResponse for ProblemDetails<Ext>
where
    Ext: serde::Serialize,
{
    fn into_response(self) -> Response {
        JsonProblemDetails(self).into_response()
    }
}