From 66d38c09f6543c365b13452fe8cd0d290a69c868 Mon Sep 17 00:00:00 2001 From: Martin Algesten Date: Fri, 27 Dec 2024 11:02:17 +0100 Subject: [PATCH 1/2] SendBody::into_reader() --- CHANGELOG.md | 1 + src/send_body.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d970205d..d4150964 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Unreleased + * Add new `SendBody::into_reader()` (#914) * Fix completely broken PEM parsing (#912) # 3.0.0-rc3 diff --git a/src/send_body.rs b/src/send_body.rs index 7749c987..ff137abd 100644 --- a/src/send_body.rs +++ b/src/send_body.rs @@ -74,6 +74,48 @@ impl<'a> SendBody<'a> { pub(crate) fn body_mode(&self) -> BodyMode { self.inner.body_mode() } + + /// Turn this `SendBody` into a reader. + /// + /// This is useful in [`Middleware`][crate::middleware::Middleware] to make changes to the + /// body before sending it. + /// + /// ``` + /// use ureq::{SendBody, Body}; + /// use ureq::middleware::MiddlewareNext; + /// use ureq::http::{Request, Response, header::HeaderValue}; + /// use std::io::Read; + /// + /// fn my_middleware(req: Request, next: MiddlewareNext) + /// -> Result, ureq::Error> { + /// + /// // Take apart the request. + /// let (parts, body) = req.into_parts(); + /// + /// // Take the first 100 bytes of the incoming send body. + /// let mut reader = body.into_reader().take(100); + /// + /// // Create a new SendBody. + /// let new_body = SendBody::from_reader(&mut reader); + /// + /// // Reconstitute the request. + /// let req = Request::from_parts(parts, new_body); + /// + /// // set my bespoke header and continue the chain + /// next.handle(req) + /// } + /// ``` + pub fn into_reader(self) -> impl Sized + io::Read + 'a { + ReadAdapter(self) + } +} + +struct ReadAdapter<'a>(SendBody<'a>); + +impl<'a> io::Read for ReadAdapter<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } } use http::Response; From 96564abb81b84527bf02e0f4a0fdd018c5dd45a6 Mon Sep 17 00:00:00 2001 From: Martin Algesten Date: Fri, 27 Dec 2024 11:04:25 +0100 Subject: [PATCH 2/2] Update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4150964..088cf3ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ * Add new `SendBody::into_reader()` (#914) * Fix completely broken PEM parsing (#912) + * Improve ergonomics for `AutoHeaderValue` (#896) # 3.0.0-rc3