Compression

Response 内容压缩处理的中间件.

提供对三种压缩格式的支持: br, gzip, deflate. 可以根据需求配置各个压缩方式的优先度等.

配置 Cargo.toml

salvo = { version = "*", features = ["compression"] }

示例代码

use salvo::compression::{Compression, CompressionAlgo};
use salvo::prelude::*;
use salvo_static::*;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().init();

    let base_dir = std::env::current_exe()
        .unwrap()
        .join("../../../examples/compression/static")
        .canonicalize()
        .unwrap();
    println!("Base Dir: {:?}", base_dir);

    let router = Router::new()
        .push(
            Router::with_hoop(Compression::new().with_force_priority(true))
                .path("ws_chat")
                .get(StaticFile::new(base_dir.join("ws_chat.txt"))),
        )
        .push(
            Router::with_hoop(Compression::new().with_algos(&[CompressionAlgo::Brotli]))
                .path("sse_chat")
                .get(StaticFile::new(base_dir.join("sse_chat.txt"))),
        )
        .push(
            Router::with_hoop(Compression::new().with_algos(&[CompressionAlgo::Deflate]))
                .path("todos")
                .get(StaticFile::new(base_dir.join("todos.txt"))),
        )
        .push(
            Router::with_hoop(Compression::new().with_algos(&[CompressionAlgo::Gzip]))
                .path("<*path>")
                .get(StaticDir::new(base_dir)),
        );

    let acceptor = TcpListener::new("127.0.0.1:7878").bind().await;
    Server::new(acceptor).serve(router).await;
}
[package]
name = "example-compression"
version = "0.1.0"
edition = "2021"
publish = false


[dependencies]
salvo = { git = "https://github.com/salvo-rs/salvo.git", features = ["compression", "serve-static"] }
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"