Skip to content

Commit

Permalink
Replace GZIP compression with Brotli
Browse files Browse the repository at this point in the history
  • Loading branch information
daxpedda authored and jakobhellermann committed Aug 6, 2022
1 parent 27b90da commit 2f0bbec
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 15 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ tokio = { version = "1.11", default-features = false, features = ["rt-multi-thre
tower-http = { version = "0.3", features = ["compression-full", "fs", "set-header", "trace"] }
tower = "0.4"
fastrand = "1.5"
flate2 = "1.0"
brotli = { version = "3", default-features = false, features = ["std"]}
rcgen = { version = "0.9", default-features = false }
6 changes: 3 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::net::SocketAddr;

use axum::headers::{ContentEncoding, HeaderName};
use axum::headers::HeaderName;
use axum::http::{HeaderValue, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, get_service};
use axum::{Router, TypedHeader};
use axum::Router;
use axum_server::tls_rustls::RustlsConfig;
use axum_server_dual_protocol::ServerExt;
use tower::ServiceBuilder;
Expand Down Expand Up @@ -47,7 +47,7 @@ pub async fn run_server(options: Options, output: WasmBindgenOutput) -> Result<(
let serve_dir = get_service(ServeDir::new(".")).handle_error(internal_server_error);

let serve_wasm = || async move {
(TypedHeader(ContentEncoding::gzip()), WithContentType("application/wasm", compressed_wasm))
([("content-encoding", "br")], WithContentType("application/wasm", compressed_wasm))
};

let app = Router::new()
Expand Down
16 changes: 5 additions & 11 deletions src/wasm_bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ use anyhow::Context;
use std::path::Path;
use tracing::debug;

const COMPRESSION_LEVEL: u32 = 2;

pub struct WasmBindgenOutput {
pub js: String,
pub compressed_wasm: Vec<u8>,
Expand Down Expand Up @@ -34,15 +32,11 @@ pub fn generate(wasm_file: &Path) -> Result<WasmBindgenOutput> {
Ok(WasmBindgenOutput { js, compressed_wasm })
}

fn compress(bytes: &[u8]) -> Result<Vec<u8>, std::io::Error> {
use flate2::write::GzEncoder;
use flate2::Compression;
use std::io::prelude::*;

let mut encoder = GzEncoder::new(Vec::new(), Compression::new(COMPRESSION_LEVEL));
fn compress(mut bytes: &[u8]) -> Result<Vec<u8>, std::io::Error> {
use brotli::enc::{self, BrotliEncoderParams};

encoder.write_all(bytes)?;
let compressed = encoder.finish()?;
let mut output = Vec::new();
enc::BrotliCompress(&mut bytes, &mut output, &BrotliEncoderParams::default())?;

Ok(compressed)
Ok(output)
}

0 comments on commit 2f0bbec

Please sign in to comment.