tower_http/decompression/
service.rsuse super::{DecompressionBody, DecompressionLayer, ResponseFuture};
use crate::compression_utils::AcceptEncoding;
use http::{
header::{self, ACCEPT_ENCODING},
Request, Response,
};
use http_body::Body;
use std::task::{Context, Poll};
use tower_service::Service;
#[derive(Debug, Clone)]
pub struct Decompression<S> {
pub(crate) inner: S,
pub(crate) accept: AcceptEncoding,
}
impl<S> Decompression<S> {
pub fn new(service: S) -> Self {
Self {
inner: service,
accept: AcceptEncoding::default(),
}
}
define_inner_service_accessors!();
pub fn layer() -> DecompressionLayer {
DecompressionLayer::new()
}
#[cfg(feature = "decompression-gzip")]
pub fn gzip(mut self, enable: bool) -> Self {
self.accept.set_gzip(enable);
self
}
#[cfg(feature = "decompression-deflate")]
pub fn deflate(mut self, enable: bool) -> Self {
self.accept.set_deflate(enable);
self
}
#[cfg(feature = "decompression-br")]
pub fn br(mut self, enable: bool) -> Self {
self.accept.set_br(enable);
self
}
#[cfg(feature = "decompression-zstd")]
pub fn zstd(mut self, enable: bool) -> Self {
self.accept.set_zstd(enable);
self
}
pub fn no_gzip(mut self) -> Self {
self.accept.set_gzip(false);
self
}
pub fn no_deflate(mut self) -> Self {
self.accept.set_deflate(false);
self
}
pub fn no_br(mut self) -> Self {
self.accept.set_br(false);
self
}
pub fn no_zstd(mut self) -> Self {
self.accept.set_zstd(false);
self
}
}
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for Decompression<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
ResBody: Body,
{
type Response = Response<DecompressionBody<ResBody>>;
type Error = S::Error;
type Future = ResponseFuture<S::Future>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
if let header::Entry::Vacant(entry) = req.headers_mut().entry(ACCEPT_ENCODING) {
if let Some(accept) = self.accept.to_header_value() {
entry.insert(accept);
}
}
ResponseFuture {
inner: self.inner.call(req),
accept: self.accept,
}
}
}