typestar

Nesting and fallbacks in Rust

Routers compose: nest a sub-router under a prefix and give the rest a fallback.

use axum::http::StatusCode;
use axum::{routing::get, Router};

fn api() -> Router {
    Router::new()
        .route("/tours", get(|| async { "tour list" }))
        .route("/stats", get(|| async { "your stats" }))
}

async fn missing() -> (StatusCode, &'static str) {
    (StatusCode::NOT_FOUND, "nothing here")
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "typestar" }))
        .nest("/api", api())
        .fallback(missing);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

How it works

  1. nest mounts one router under a path prefix.
  2. merge combines routers that share a namespace.
  3. fallback answers everything that matched nothing.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
558
Tokens
186
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 106 seconds.

Type this snippet

Step 3 of 3 in Routes & handlers, step 3 of 9 in Web services with axum.

← Previous Next →