use tower_http::compression::CompressionLayer as TowerCompressionLayer;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompressionAlgorithm {
Gzip,
Brotli,
Deflate,
}
#[derive(Debug, Clone)]
pub struct CompressionConfig {
pub enable_gzip: bool,
pub enable_brotli: bool,
pub enable_deflate: bool,
}
impl Default for CompressionConfig {
fn default() -> Self {
Self { enable_gzip: true, enable_brotli: true, enable_deflate: true }
}
}
impl CompressionConfig {
pub fn new() -> Self {
Self::default()
}
pub fn with_gzip(mut self, enable: bool) -> Self {
self.enable_gzip = enable;
self
}
pub fn with_brotli(mut self, enable: bool) -> Self {
self.enable_brotli = enable;
self
}
pub fn with_deflate(mut self, enable: bool) -> Self {
self.enable_deflate = enable;
self
}
}
pub struct Compression {
config: CompressionConfig,
}
impl Compression {
pub fn new() -> Self {
Self { config: CompressionConfig::new() }
}
pub fn with_config(config: CompressionConfig) -> Self {
Self { config }
}
pub fn config(&self) -> &CompressionConfig {
&self.config
}
pub fn build(&self) -> TowerCompressionLayer {
let mut layer = TowerCompressionLayer::new();
if self.config.enable_gzip {
layer = layer.gzip(true);
}
if self.config.enable_brotli {
layer = layer.br(true);
}
if self.config.enable_deflate {
layer = layer.deflate(true);
}
layer
}
}
impl Default for Compression {
fn default() -> Self {
Self::new()
}
}
pub struct CompressionBuilder {
config: CompressionConfig,
}
impl CompressionBuilder {
pub fn new() -> Self {
Self { config: CompressionConfig::new() }
}
pub fn gzip(mut self) -> Self {
self.config.enable_gzip = true;
self
}
pub fn no_gzip(mut self) -> Self {
self.config.enable_gzip = false;
self
}
pub fn brotli(mut self) -> Self {
self.config.enable_brotli = true;
self
}
pub fn no_brotli(mut self) -> Self {
self.config.enable_brotli = false;
self
}
pub fn deflate(mut self) -> Self {
self.config.enable_deflate = true;
self
}
pub fn no_deflate(mut self) -> Self {
self.config.enable_deflate = false;
self
}
pub fn build(self) -> Compression {
Compression::with_config(self.config)
}
}
impl Default for CompressionBuilder {
fn default() -> Self {
Self::new()
}
}