use std::sync::Arc;
use actix_web::{web, HttpMessage, HttpRequest};
use crate::error::XMLPayloadError;
#[derive(Clone)]
pub struct XmlConfig {
pub(crate) limit: usize,
content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
}
const DEFAULT_CONFIG: XmlConfig = XmlConfig {
limit: 262_144,
content_type: None,
};
impl Default for XmlConfig {
fn default() -> Self {
DEFAULT_CONFIG.clone()
}
}
impl XmlConfig {
pub fn new() -> Self {
Default::default()
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
pub fn content_type<F>(mut self, predicate: F) -> Self
where
F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
{
self.content_type = Some(Arc::new(predicate));
self
}
pub(crate) fn check_content_type(&self, req: &HttpRequest) -> Result<(), XMLPayloadError> {
if let Ok(Some(mime)) = req.mime_type() {
if mime == "text/xml"
|| mime == "application/xml"
|| self
.content_type
.as_ref()
.map_or(false, |predicate| predicate(mime))
{
Ok(())
} else {
Err(XMLPayloadError::ContentType)
}
} else {
Err(XMLPayloadError::ContentType)
}
}
pub(crate) fn from_req(req: &HttpRequest) -> &Self {
req.app_data::<Self>()
.or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref()))
.unwrap_or(&DEFAULT_CONFIG)
}
}