Skip to content

Commit

Permalink
[OPTIMIZATION] maxbodysize
Browse files Browse the repository at this point in the history
  • Loading branch information
ismoilovdevml committed Oct 15, 2023
1 parent 02d8c20 commit 4a9f0c4
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions src/middleware/maxbodysize.rs
Original file line number Diff line number Diff line change
@@ -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<Body>,
_context: &Context<'_>,
) -> Result<Request<Body>, Response<Body>> {
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<Body>,
_context: &Context<'_>,
) -> Result<Request<Body>, Response<Body>> {
// 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::<i64>() {
if parsed_length > self.limit {
return Err(error_response::request_entity_to_large());
}
}
}
}
Ok(request)
}
}
}

fn get_content_length(headers: &HeaderMap) -> Option<i64> {
headers.get(CONTENT_LENGTH)?.to_str().ok()?.parse().ok()
}

0 comments on commit 4a9f0c4

Please sign in to comment.