Skip to content

Commit 8202c66

Browse files
Add DefaultBodyLimit::apply (#3368)
1 parent 7eabf7e commit 8202c66

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

axum-core/CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
# Unreleased
9+
10+
- **added:** `DefaultBodyLimit::apply` for changing the `DefaultBodyLimit` inside extractors.
11+
([#3368])
12+
13+
[#3368]: https://github.com/tokio-rs/axum/pull/3366
14+
815
# 0.5.2
916

1017
- **added:** Implement `Stream::size_hint` for `BodyDataStream` ([#3195])

axum-core/src/extract/default_body_limit.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use self::private::DefaultBodyLimitService;
2+
use http::Request;
23
use tower_layer::Layer;
34

45
/// Layer for configuring the default request body limit.
@@ -151,6 +152,36 @@ impl DefaultBodyLimit {
151152
kind: DefaultBodyLimitKind::Limit(limit),
152153
}
153154
}
155+
156+
/// Apply a request body limit to the given request.
157+
///
158+
/// This can be used, for example, to modify the default body limit inside a specific
159+
/// extractor.
160+
///
161+
/// # Example
162+
///
163+
/// An extractor similar to [`Bytes`](bytes::Bytes), but limiting the body to 1 KB.
164+
///
165+
/// ```
166+
/// use axum::{
167+
/// extract::{DefaultBodyLimit, FromRequest, rejection::BytesRejection, Request},
168+
/// body::Bytes,
169+
/// };
170+
///
171+
/// struct Bytes1KB(Bytes);
172+
///
173+
/// impl<S: Sync> FromRequest<S> for Bytes1KB {
174+
/// type Rejection = BytesRejection;
175+
///
176+
/// async fn from_request(mut req: Request, _: &S) -> Result<Self, Self::Rejection> {
177+
/// DefaultBodyLimit::max(1024).apply(&mut req);
178+
/// Ok(Self(Bytes::from_request(req, &()).await?))
179+
/// }
180+
/// }
181+
/// ```
182+
pub fn apply<B>(self, req: &mut Request<B>) {
183+
req.extensions_mut().insert(self.kind);
184+
}
154185
}
155186

156187
impl<S> Layer<S> for DefaultBodyLimit {

0 commit comments

Comments
 (0)