-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
02d8c20
commit 4a9f0c4
Showing
1 changed file
with
20 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} |