diff --git a/axum-core/CHANGELOG.md b/axum-core/CHANGELOG.md index cd59a078..10e99e56 100644 --- a/axum-core/CHANGELOG.md +++ b/axum-core/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +# Unreleased + +- **added:** `DefaultBodyLimit::apply` for changing the `DefaultBodyLimit` inside extractors. + ([#3368]) + +[#3368]: https://github.com/tokio-rs/axum/pull/3366 + # 0.5.2 - **added:** Implement `Stream::size_hint` for `BodyDataStream` ([#3195]) diff --git a/axum-core/src/extract/default_body_limit.rs b/axum-core/src/extract/default_body_limit.rs index b3fed6b8..bb1f44bf 100644 --- a/axum-core/src/extract/default_body_limit.rs +++ b/axum-core/src/extract/default_body_limit.rs @@ -1,4 +1,5 @@ use self::private::DefaultBodyLimitService; +use http::Request; use tower_layer::Layer; /// Layer for configuring the default request body limit. @@ -151,6 +152,36 @@ impl DefaultBodyLimit { kind: DefaultBodyLimitKind::Limit(limit), } } + + /// Apply a request body limit to the given request. + /// + /// This can be used, for example, to modify the default body limit inside a specific + /// extractor. + /// + /// # Example + /// + /// An extractor similar to [`Bytes`](bytes::Bytes), but limiting the body to 1 KB. + /// + /// ``` + /// use axum::{ + /// extract::{DefaultBodyLimit, FromRequest, rejection::BytesRejection, Request}, + /// body::Bytes, + /// }; + /// + /// struct Bytes1KB(Bytes); + /// + /// impl FromRequest for Bytes1KB { + /// type Rejection = BytesRejection; + /// + /// async fn from_request(mut req: Request, _: &S) -> Result { + /// DefaultBodyLimit::max(1024).apply(&mut req); + /// Ok(Self(Bytes::from_request(req, &()).await?)) + /// } + /// } + /// ``` + pub fn apply(self, req: &mut Request) { + req.extensions_mut().insert(self.kind); + } } impl Layer for DefaultBodyLimit {