Skip to content
Myr

main.rs

This file

Path

examples/validator/src/main.rs

168 lines · 4.7 KiB · Rust

Last changed by

examples: Update name validation message (#3873)tottotobefore adoptioned82333

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-validator5//!6//! curl '127.0.0.1:3000?name='7//! -> Input validation error: [name: Must be at least 2 characters]8//!9//! curl '127.0.0.1:3000?name=LT'10//! -> <h1>Hello, LT!</h1>11//! ```1213use axum::{14    extract::{rejection::FormRejection, Form, FromRequest, Request},15    http::StatusCode,16    response::{Html, IntoResponse, Response},17    routing::get,18    Router,19};20use serde::{de::DeserializeOwned, Deserialize};21use thiserror::Error;22use tokio::net::TcpListener;23use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};24use validator::Validate;2526#[tokio::main]27async fn main() {28    tracing_subscriber::registry()29        .with(30            tracing_subscriber::EnvFilter::try_from_default_env()31                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),32        )33        .with(tracing_subscriber::fmt::layer())34        .init();3536    // build our application with a route37    let app = app();3839    // run it40    let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();41    tracing::debug!("listening on {}", listener.local_addr().unwrap());42    axum::serve(listener, app).await;43}4445fn app() -> Router {46    Router::new().route("/", get(handler))47}4849#[derive(Debug, Deserialize, Validate)]50pub struct NameInput {51    #[validate(length(min = 2, message = "Must be at least 2 characters"))]52    pub name: String,53}5455async fn handler(ValidatedForm(input): ValidatedForm<NameInput>) -> Html<String> {56    Html(format!("<h1>Hello, {}!</h1>", input.name))57}5859#[derive(Debug, Clone, Copy, Default)]60pub struct ValidatedForm<T>(pub T);6162impl<T, S> FromRequest<S> for ValidatedForm<T>63where64    T: DeserializeOwned + Validate,65    S: Send + Sync,66    Form<T>: FromRequest<S, Rejection = FormRejection>,67{68    type Rejection = ServerError;6970    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {71        let Form(value) = Form::<T>::from_request(req, state).await?;72        value.validate()?;73        Ok(ValidatedForm(value))74    }75}7677#[derive(Debug, Error)]78pub enum ServerError {79    #[error(transparent)]80    ValidationError(#[from] validator::ValidationErrors),8182    #[error(transparent)]83    AxumFormRejection(#[from] FormRejection),84}8586impl IntoResponse for ServerError {87    fn into_response(self) -> Response {88        match self {89            ServerError::ValidationError(_) => {90                let message = format!("Input validation error: [{self}]").replace('\n', ", ");91                (StatusCode::BAD_REQUEST, message)92            }93            ServerError::AxumFormRejection(_) => (StatusCode::BAD_REQUEST, self.to_string()),94        }95        .into_response()96    }97}9899#[cfg(test)]100mod tests {101    use super::*;102    use axum::{103        body::Body,104        http::{Request, StatusCode},105    };106    use http_body_util::BodyExt;107    use tower::ServiceExt;108109    async fn get_html(response: Response<Body>) -> String {110        let body = response.into_body();111        let bytes = body.collect().await.unwrap().to_bytes();112        String::from_utf8(bytes.to_vec()).unwrap()113    }114115    #[tokio::test]116    async fn test_no_param() {117        let response = app()118            .oneshot(Request::get("/").body(Body::empty()).unwrap())119            .await120            .unwrap();121122        assert_eq!(response.status(), StatusCode::BAD_REQUEST);123        let html = get_html(response).await;124        assert_eq!(html, "Failed to deserialize form: missing field `name`");125    }126127    #[tokio::test]128    async fn test_with_param_without_value() {129        let response = app()130            .oneshot(Request::get("/?name=").body(Body::empty()).unwrap())131            .await132            .unwrap();133134        assert_eq!(response.status(), StatusCode::BAD_REQUEST);135        let html = get_html(response).await;136        assert_eq!(137            html,138            "Input validation error: [name: Must be at least 2 characters]"139        );140    }141142    #[tokio::test]143    async fn test_with_param_with_short_value() {144        let response = app()145            .oneshot(Request::get("/?name=X").body(Body::empty()).unwrap())146            .await147            .unwrap();148149        assert_eq!(response.status(), StatusCode::BAD_REQUEST);150        let html = get_html(response).await;151        assert_eq!(152            html,153            "Input validation error: [name: Must be at least 2 characters]"154        );155    }156157    #[tokio::test]158    async fn test_with_param_and_value() {159        let response = app()160            .oneshot(Request::get("/?name=LT").body(Body::empty()).unwrap())161            .await162            .unwrap();163164        assert_eq!(response.status(), StatusCode::OK);165        let html = get_html(response).await;166        assert_eq!(html, "<h1>Hello, LT!</h1>");167    }168}