Skip to content

Instantly share code, notes, and snippets.

@jmwample
Created February 12, 2025 16:45
Show Gist options
  • Save jmwample/c15a983e804fc338fee3d1b037d216b0 to your computer and use it in GitHub Desktop.
Save jmwample/c15a983e804fc338fee3d1b037d216b0 to your computer and use it in GitHub Desktop.
Axum Json compression Example

Axum Json compression test

Send a Get request for plain data

curl -vvv -X 'GET' \
  'http://localhost:3000/json' \
  -H 'accept: application/json' -H "Connection: close" --output test.json

Send a Get request for The same data, indicating a preference for gzip encoding.

curl -vvv -X 'GET' \
  'http://localhost:3000/json' \
  -H 'accept: application/json' -H "accept-encoding: gzip;q=1.0, *;q=0.5" -H "Connection: close" --output test.json.gz
[package]
name = "axum"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.1"
tower-http = { version="0.6.2", features = ["cors", "trace", "compression-br", "compression-deflate", "compression-gzip", "compression-zstd"] }
tokio = { version = "1.43.0", features = ["full"]}
serde = { version = "1.0.217", features = ["serde_derive"]}
serde_json = "1.0"
use axum::{response::Json, routing::get, Router};
use serde::{Deserialize, Serialize};
use tower_http::compression::CompressionLayer;
#[derive(Serialize, Deserialize)]
struct Node {
id: u64,
pubkey: [u8; 32],
}
#[tokio::main]
async fn main() {
let compression_layer = CompressionLayer::new()
.br(true)
.deflate(true)
.gzip(true)
.zstd(true);
// our router
let app = Router::new()
.route("/plain_text", get(plain_text))
.route("/json", get(json))
.layer(compression_layer);
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
// `&'static str` becomes a `200 OK` with `content-type: text/plain; charset=utf-8`
async fn plain_text() -> &'static str {
"foo"
}
// `Json` gives a content-type of `application/json` and works with any type
// that implements `serde::Serialize`
async fn json() -> Json<Vec<Node>> {
let response: Vec<Node> = (0..200)
.map(|id| Node {
id,
pubkey: [0u8; 32],
})
.collect();
Json(response)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment