typestar

Extractores Path y Query en Rust

Los extractores tipados desarman por ti las partes de una URL.

use axum::extract::{Path, Query};
use axum::{routing::get, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct Filter {
    lang: String,
    #[serde(default)]
    min_steps: usize,
}

async fn step(Path((tour, idx)): Path<(String, u32)>) -> String {
    format!("{tour} step {idx}")
}

async fn tours(Query(filter): Query<Filter>) -> String {
    format!("{} with at least {} steps", filter.lang, filter.min_steps)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/tours/{tour}/steps/{idx}", get(step))
        .route("/tours", get(tours));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Cómo funciona

  1. Path desestructura los marcadores de la ruta.
  2. Query deserializa la cadena de consulta en un struct.
  3. Un valor ausente o imposible de parsear se rechaza automáticamente.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
29
Caracteres a escribir
670
Tokens
191
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 104 segundos.

Escribe este fragmento

Paso 1 de 2 en Extractores y estado; paso 4 de 9 en Servicios web con axum.

← Anterior Siguiente →