expression

Axum: normalize and validate text

Normalize input only when the application contract allows it. This example trims leading and trailing whitespace, then limits the number of Unicode scalar values. Scalar values are not grapheme clusters or byte length; choose the unit deliberately. In-memory standalone Cargo example. Expected stdout (not executed): 422 200 422 Common mistake: Trimming passwords or other opaque values without an explicit contract; calling chars().count() a count of visible characters.

Formal Syntax & Structure

rust syntaxrust
let name = input.name.trim();

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{Json, routing::post};    #[derive(serde::Deserialize)] struct Input { name: String }    async fn check(Json(x): Json<Input>) -> StatusCode {        let name = x.name.trim();        if (1..=12).contains(&name.chars().count()) { StatusCode::OK } else { StatusCode::UNPROCESSABLE_ENTITY }    }    let app = Router::new().route("/check", post(check));    for body in [r#"{"name":"  "}"#, r#"{"name":"  Ada  "}"#, r#"{"name":"abcdefghijklmn"}"#] {        let r = app.clone().oneshot(Request::builder().method("POST").uri("/check").header("content-type", "application/json").body(Body::from(body)).unwrap()).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference