Module rama::http::layer::map_response_body
Expand description
Apply a transformation to the response body.
§Example
use bytes::Bytes;
use rama_http::{Body, Request, Response};
use rama_http::dep::http_body;
use std::convert::Infallible;
use std::{pin::Pin, task::{Context, Poll}};
use rama_core::{Layer, Service, context};
use rama_core::service::service_fn;
use rama_http::layer::map_response_body::MapResponseBodyLayer;
use rama_core::error::BoxError;
use futures_lite::ready;
// A wrapper for a `http_body::Body` that prints the size of data chunks
pin_project_lite::pin_project! {
struct PrintChunkSizesBody<B> {
#[pin]
inner: B,
}
}
impl<B> PrintChunkSizesBody<B> {
fn new(inner: B) -> Self {
Self { inner }
}
}
impl<B> http_body::Body for PrintChunkSizesBody<B>
where B: http_body::Body<Data = Bytes, Error = BoxError>,
{
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
let inner_body = self.as_mut().project().inner;
if let Some(frame) = ready!(inner_body.poll_frame(cx)?) {
if let Some(chunk) = frame.data_ref() {
println!("chunk size = {}", chunk.len());
} else {
eprintln!("no data chunk found");
}
Poll::Ready(Some(Ok(frame)))
} else {
Poll::Ready(None)
}
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
}
async fn handle(_: Request) -> Result<Response, Infallible> {
// ...
}
let mut svc = (
// Wrap response bodies in `PrintChunkSizesBody`
MapResponseBodyLayer::new(PrintChunkSizesBody::new),
).layer(service_fn(handle));
// Call the service
let request = Request::new(Body::from("foobar"));
svc.serve(context::Context::default(), request).await?;
Structs§
- Apply a transformation to the response body.
- Apply a transformation to the response body.