Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new SendBody::into_reader() #914

Merged
merged 2 commits into from
Dec 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Unreleased

* Add new `SendBody::into_reader()` (#914)
* Fix completely broken PEM parsing (#912)
* Improve ergonomics for `AutoHeaderValue` (#896)

# 3.0.0-rc3

Expand Down
42 changes: 42 additions & 0 deletions src/send_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SendBody>, next: MiddlewareNext)
/// -> Result<Response<Body>, 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<usize> {
self.0.read(buf)
}
}

use http::Response;
Expand Down
Loading