From 4a9f0c4b80f0e0c5693a19dd82b6d25a50fcf123 Mon Sep 17 00:00:00 2001 From: ismoilovdevml Date: Sun, 15 Oct 2023 20:31:14 +0500 Subject: [PATCH] [OPTIMIZATION] maxbodysize --- src/middleware/maxbodysize.rs | 36 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/middleware/maxbodysize.rs b/src/middleware/maxbodysize.rs index 9069a55..d9dc906 100644 --- a/src/middleware/maxbodysize.rs +++ b/src/middleware/maxbodysize.rs @@ -1,26 +1,30 @@ use super::{super::error_response, Context, Middleware}; use async_trait::async_trait; -use hyper::{header::CONTENT_LENGTH, Body, HeaderMap, Request, Response}; +use hyper::{header::CONTENT_LENGTH, Body, Request, Response}; -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub struct MaxBodySize { - pub(crate) limit: i64, + pub(crate) limit: i64, } #[async_trait] impl Middleware for MaxBodySize { - async fn modify_request( - &self, - request: Request, - _context: &Context<'_>, - ) -> Result, Response> { - match get_content_length(request.headers()) { - Some(length) if length > self.limit => Err(error_response::request_entity_to_large()), - _ => Ok(request), + async fn modify_request( + &self, + request: Request, + _context: &Context<'_>, + ) -> Result, Response> { + // Directly check the content length and compare to the limit. + // This avoids multiple function calls and streamlines the check. + if let Some(length) = request.headers().get(CONTENT_LENGTH) { + if let Ok(s) = length.to_str() { + if let Ok(parsed_length) = s.parse::() { + if parsed_length > self.limit { + return Err(error_response::request_entity_to_large()); + } + } + } + } + Ok(request) } - } -} - -fn get_content_length(headers: &HeaderMap) -> Option { - headers.get(CONTENT_LENGTH)?.to_str().ok()?.parse().ok() } \ No newline at end of file