Anidar y fallbacks en Rust
Los routers se componen: anida un sub-router bajo un prefijo y dale al resto un 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();
}
Cómo funciona
nestmonta un router bajo un prefijo de ruta.mergecombina routers que comparten un espacio de nombres.fallbackcontesta todo lo que no coincidió con nada.
Palabras clave y builtins usados aquí
asyncawaitfnletstaticstruse
El intento, en números
- Líneas
- 25
- Caracteres a escribir
- 558
- Tokens
- 186
- Ritmo de tres estrellas
- 105 tpm
Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 106 segundos.
Paso 3 de 3 en Rutas y handlers; paso 3 de 9 en Servicios web con axum.