#![allow(clippy::module_name_repetitions)]
use std::ops::{Deref, DerefMut};
use axum_core::extract::FromRequest;
use axum_core::response::{IntoResponse, Response};
use bytes::Bytes;
use http::{header, HeaderValue, Request, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::rejection::XmlRejection;
mod rejection;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, Default)]
pub struct Xml<T>(pub T);
impl<T, S> FromRequest<S> for Xml<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = XmlRejection;
async fn from_request(
req: Request<axum_core::body::Body>,
state: &S,
) -> Result<Self, Self::Rejection> {
if xml_content_type(&req) {
let bytes = Bytes::from_request(req, state).await?;
let value = quick_xml::de::from_reader(&*bytes)?;
Ok(Self(value))
} else {
Err(XmlRejection::MissingXMLContentType)
}
}
}
fn xml_content_type(req: &Request<axum_core::body::Body>) -> bool {
let Some(content_type) = req.headers().get(header::CONTENT_TYPE) else {
return false;
};
let Ok(content_type) = content_type.to_str() else {
return false;
};
let Ok(mime) = content_type.parse::<mime::Mime>() else {
return false;
};
let is_xml_content_type = (mime.type_() == "application" || mime.type_() == "text")
&& (mime.subtype() == "xml" || mime.suffix().is_some_and(|name| name == "xml"));
is_xml_content_type
}
impl<T> Deref for Xml<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for Xml<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<T> From<T> for Xml<T> {
fn from(inner: T) -> Self {
Self(inner)
}
}
impl<T> IntoResponse for Xml<T>
where
T: Serialize,
{
fn into_response(self) -> Response {
match quick_xml::se::to_string(&self.0) {
Ok(xml_string) => (
[(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
)],
xml_string,
)
.into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
[(
header::CONTENT_TYPE,
HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()),
)],
err.to_string(),
)
.into_response(),
}
}
}