#![warn(missing_docs)]
use crate::{
context::HttpResponse, next::Next, req::HttpRequest, res::response_status::StatusCode,
types::MiddlewareOutput,
};
const DEFAULT_BODY_LIMIT: usize = 1024 * 1024;
pub(crate) fn body_limit(
config: Option<usize>,
) -> impl Fn(HttpRequest, HttpResponse, Next) -> MiddlewareOutput + Send + Sync + 'static {
let config = config.unwrap_or(DEFAULT_BODY_LIMIT);
move |req: HttpRequest, res, _| {
Box::pin(async move {
let body = req.clone().body;
if body.len() > config {
eprintln!(
"Body limit exceeded: {} bytes > {} bytes",
body.len(),
config
);
return (req, Some(res.status(StatusCode::PayloadTooLarge.as_u16()).json(serde_json::json!({
"error": "Request body too large",
"message": format!("Request body exceeded the configured limit of {} bytes", config),
"limit": config,
"received": body.len()
}))));
}
return (req, None);
})
}
}