Module rama::http::layer::decompression

Expand description

Middleware that decompresses request and response bodies.

§Examples

§Request
use std::{error::Error, io::Write};

use bytes::{Bytes, BytesMut};
use flate2::{write::GzEncoder, Compression};

use rama_http::{Body, header, HeaderValue, Request, Response};
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};
use rama_http::layer::decompression::{DecompressionBody, RequestDecompressionLayer};
use rama_http::dep::http_body_util::BodyExt;
use rama_core::error::BoxError;

// A request encoded with gzip coming from some HTTP client.
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
encoder.write_all(b"Hello?")?;
let request = Request::builder()
    .header(header::CONTENT_ENCODING, "gzip")
    .body(Body::from(encoder.finish()?))?;

// Our HTTP server
let mut server = (
    // Automatically decompress request bodies.
    RequestDecompressionLayer::new(),
).layer(service_fn(handler));

// Send the request, with the gzip encoded body, to our server.
let _response = server.serve(Context::default(), request).await?;

// Handler receives request whose body is decoded when read
async fn handler(mut req: Request<DecompressionBody<Body>>) -> Result<Response, BoxError>{
    let data = req.into_body().collect().await?.to_bytes();
    assert_eq!(&data[..], b"Hello?");
    Ok(Response::new(Body::from("Hello, World!")))
}
§Response
use std::convert::Infallible;

use bytes::{Bytes, BytesMut};

use rama_http::{Body, Request, Response};
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};
use rama_http::layer::{compression::Compression, decompression::DecompressionLayer};
use rama_http::dep::http_body_util::BodyExt;
use rama_core::error::BoxError;


// Some opaque service that applies compression.
let service = Compression::new(service_fn(handle));

// Our HTTP client.
let mut client = (
    // Automatically decompress response bodies.
    DecompressionLayer::new(),
).layer(service);

// Call the service.
//
// `DecompressionLayer` takes care of setting `Accept-Encoding`.
let request = Request::new(Body::default());

let response = client
    .serve(Context::default(), request)
    .await?;

// Read the body
let body = response.into_body();
let bytes = body.collect().await?.to_bytes().to_vec();
let body = String::from_utf8(bytes).map_err(Into::<BoxError>::into)?;

assert_eq!(body, "Hello, World!");

Structs§