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 fileTake it
The walk stopped after 200 commits: lines older than f9c0e70 point at it.
examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 1–6why, one step back1//! Run with2//!3//! ```not_rust4//! cargo run -p example-validator5//!6//! curl '127.0.0.1:3000?name='examples: Update name validation message (#3873)tottotobefore adoptioned82333
line 7why, one step back7//! -> Input validation error: [name: Must be at least 2 characters]examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 8–41why, one step back8//!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());Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7
line 42why, one step back42 axum::serve(listener, app).await;examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 43–50why, one step back43}4445fn app() -> Router {46 Router::new().route("/", get(handler))47}4849#[derive(Debug, Deserialize, Validate)]50pub struct NameInput {examples: Update name validation message (#3873)tottotobefore adoptioned82333
line 51why, one step back51 #[validate(length(min = 2, message = "Must be at least 2 characters"))]examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 52–117why, one step back52 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()examples: Simplify Request and Response construction (#3653)tottotobefore adoption3f8956d
line 118why, one step back118 .oneshot(Request::get("/").body(Body::empty()).unwrap())examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 119–129why, one step back119 .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()examples: Simplify Request and Response construction (#3653)tottotobefore adoption3f8956d
line 130why, one step back130 .oneshot(Request::get("/?name=").body(Body::empty()).unwrap())examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 131–135why, one step back131 .await132 .unwrap();133134 assert_eq!(response.status(), StatusCode::BAD_REQUEST);135 let html = get_html(response).await;examples: Update name validation message (#3873)tottotobefore adoptioned82333
lines 136–139why, one step back136 assert_eq!(137 html,138 "Input validation error: [name: Must be at least 2 characters]"139 );examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 140–144why, one step back140 }141142 #[tokio::test]143 async fn test_with_param_with_short_value() {144 let response = app()examples: Simplify Request and Response construction (#3653)tottotobefore adoption3f8956d
line 145why, one step back145 .oneshot(Request::get("/?name=X").body(Body::empty()).unwrap())examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 146–150why, one step back146 .await147 .unwrap();148149 assert_eq!(response.status(), StatusCode::BAD_REQUEST);150 let html = get_html(response).await;examples: Update name validation message (#3873)tottotobefore adoptioned82333
lines 151–154why, one step back151 assert_eq!(152 html,153 "Input validation error: [name: Must be at least 2 characters]"154 );examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 155–159why, one step back155 }156157 #[tokio::test]158 async fn test_with_param_and_value() {159 let response = app()examples: Simplify Request and Response construction (#3653)tottotobefore adoption3f8956d
line 160why, one step back160 .oneshot(Request::get("/?name=LT").body(Body::empty()).unwrap())examples: Update to jsonwebtoken 10 (#3520)tottotobefore adoptionf9c0e70
lines 161–168why, one step back161 .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}