Skip to main content

tako_rs_extractors/
bytes.rs

1//! Raw request body access for HTTP requests.
2//!
3//! This module provides the [`Bytes`](crate::bytes::Bytes) extractor for accessing the raw HTTP request body
4//! as a `hyper::body::Incoming` stream. This is useful when you need low-level access
5//! to the request body stream for custom processing, streaming, or when working directly
6//! with hyper's body types.
7//!
8//! # Examples
9//!
10//! ```rust
11//! use tako::extractors::bytes::Bytes;
12//! use tako::types::Request;
13//! use http_body_util::BodyExt;
14//!
15//! async fn handle_raw_body(Bytes(body): Bytes<'_>) {
16//!     // Access the raw hyper body stream
17//!     println!("Got access to raw body stream");
18//!
19//!     // You can use hyper's body utilities to read the body
20//!     // let full_body = body.collect().await.unwrap();
21//!     // let bytes = full_body.to_bytes();
22//! }
23//! ```
24
25use std::convert::Infallible;
26
27use tako_rs_core::body::TakoBody;
28use tako_rs_core::extractors::FromRequest;
29use tako_rs_core::types::Request;
30
31/// Raw request body extractor that provides access to the underlying body stream.
32///
33/// This extractor wraps a reference to the raw request body implementing `http_body::Body`,
34/// allowing direct access to the request body without buffering.
35///
36/// **Naming note**: this `Bytes<'a>` is distinct from the very-common
37/// [`bytes::Bytes`](https://docs.rs/bytes/) type from the `bytes` crate
38/// (which is a refcounted byte buffer, not a body reference). In handlers
39/// that need both, import this as
40/// `use tako::extractors::bytes::Bytes as BytesBody;` to avoid the clash.
41#[doc(alias = "bytes")]
42pub struct Bytes<'a>(pub &'a mut TakoBody);
43
44impl<'a> FromRequest<'a> for Bytes<'a> {
45  type Error = Infallible;
46
47  fn from_request(
48    req: &'a mut Request,
49  ) -> impl core::future::Future<Output = core::result::Result<Self, Self::Error>> + Send + 'a {
50    futures_util::future::ready(Ok(Bytes(req.body_mut())))
51  }
52}