Path and Query extractors in Rust
Typed extractors pull the parts of a URL apart for you.
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();
}
How it works
Pathdestructures the placeholders in the route.Querydeserializes the query string into a struct.- A missing or unparsable value is rejected automatically.
Keywords and builtins used here
FilterPathQueryStringasyncawaitfnletmainstepstructtoursu32useusize
The run, in numbers
- Lines
- 29
- Characters to type
- 670
- Tokens
- 191
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 104 seconds.
Step 1 of 2 in Extractors & state, step 4 of 9 in Web services with axum.