Cookbook / Production

Using tower middleware

Plug in any tower layer, including all of tower-http, and run Axeon as a tower Service.

Axeon speaks tower, so the ecosystem's middleware works as is: timeouts, tracing, decompression, header manipulation and more. Add a layer with app.layer(..).

Terminal
cargo add tower-http --features timeout,set-header,decompression-gzip
cargo add http
src/main.rs
use axeon::Server;
use http::{header, HeaderValue, StatusCode};
use std::time::Duration;
use tower_http::set_header::SetResponseHeaderLayer;
use tower_http::timeout::TimeoutLayer;

fn main() {
    let mut app = Server::new();

    // Answer 408 if a handler takes longer than 10 seconds.
    app.layer(TimeoutLayer::with_status_code(
        StatusCode::REQUEST_TIMEOUT,
        Duration::from_secs(10),
    ));

    // Add a header to every response.
    app.layer(SetResponseHeaderLayer::overriding(
        header::HeaderName::from_static("x-served-by"),
        HeaderValue::from_static("axeon"),
    ));

    app.get("/", |_req| async { "hello" });
    app.get("/slow", |_req| async {
        tokio::time::sleep(Duration::from_secs(30)).await;
        "too late"
    });

    app.listen("127.0.0.1:3000").expect("server failed to start");
}

Notes#

  • app.layer(..) and app.middleware(..) can be mixed freely; they run in the order they are added.
  • To host an Axeon app inside another server, build it with into_app() and call into_service() for a tower Service.