mirror of
https://github.com/tokio-rs/axum.git
synced 2025-09-29 22:10:59 +00:00
Add validator example (#352)
This commit is contained in:
parent
0b3ee5b2ce
commit
3adc8d733d
16
examples/validator/Cargo.toml
Normal file
16
examples/validator/Cargo.toml
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
edition = "2018"
|
||||||
|
name = "example-validator"
|
||||||
|
publish = false
|
||||||
|
version = "0.1.0"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
async-trait = "0.1"
|
||||||
|
axum = { path = "../.." }
|
||||||
|
http-body = "0.4.3"
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
thiserror = "1.0.29"
|
||||||
|
tokio = { version = "1.0", features = ["full"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = "0.2"
|
||||||
|
validator = { version = "0.14.0", features = ["derive"] }
|
100
examples/validator/src/main.rs
Normal file
100
examples/validator/src/main.rs
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
//! Run with
|
||||||
|
//!
|
||||||
|
//! ```not_rust
|
||||||
|
//! cargo run -p example-validator
|
||||||
|
//!
|
||||||
|
//! curl '127.0.0.1:3000?name='
|
||||||
|
//! -> Input validation error: [name: Can not be empty]
|
||||||
|
//!
|
||||||
|
//! curl '127.0.0.1:3000?name=LT'
|
||||||
|
//! -> <h1>Hello, LT!</h1>
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use axum::{
|
||||||
|
body::{Bytes, Full},
|
||||||
|
extract::{Form, FromRequest, RequestParts},
|
||||||
|
handler::get,
|
||||||
|
http::{Response, StatusCode},
|
||||||
|
response::{Html, IntoResponse},
|
||||||
|
BoxError, Router,
|
||||||
|
};
|
||||||
|
use serde::{de::DeserializeOwned, Deserialize};
|
||||||
|
use std::{convert::Infallible, net::SocketAddr};
|
||||||
|
use thiserror::Error;
|
||||||
|
use validator::Validate;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
if std::env::var_os("RUST_LOG").is_none() {
|
||||||
|
std::env::set_var("RUST_LOG", "example_validator=debug")
|
||||||
|
}
|
||||||
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
|
// build our application with a route
|
||||||
|
let app = Router::new().route("/", get(handler));
|
||||||
|
|
||||||
|
// run it
|
||||||
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||||
|
tracing::debug!("listening on {}", addr);
|
||||||
|
|
||||||
|
axum::Server::bind(&addr)
|
||||||
|
.serve(app.into_make_service())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Validate)]
|
||||||
|
pub struct NameInput {
|
||||||
|
#[validate(length(min = 1, message = "Can not be empty"))]
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handler(ValidatedForm(input): ValidatedForm<NameInput>) -> Html<String> {
|
||||||
|
Html(format!("<h1>Hello, {}!</h1>", input.name))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
|
pub struct ValidatedForm<T>(pub T);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<T, B> FromRequest<B> for ValidatedForm<T>
|
||||||
|
where
|
||||||
|
T: DeserializeOwned + Validate,
|
||||||
|
B: http_body::Body + Send,
|
||||||
|
B::Data: Send,
|
||||||
|
B::Error: Into<BoxError>,
|
||||||
|
{
|
||||||
|
type Rejection = ServerError;
|
||||||
|
|
||||||
|
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
|
||||||
|
let Form(value) = Form::<T>::from_request(req).await?;
|
||||||
|
value.validate()?;
|
||||||
|
Ok(ValidatedForm(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ServerError {
|
||||||
|
#[error(transparent)]
|
||||||
|
ValidationError(#[from] validator::ValidationErrors),
|
||||||
|
|
||||||
|
#[error(transparent)]
|
||||||
|
AxumFormRejection(#[from] axum::extract::rejection::FormRejection),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for ServerError {
|
||||||
|
type Body = Full<Bytes>;
|
||||||
|
type BodyError = Infallible;
|
||||||
|
|
||||||
|
fn into_response(self) -> Response<Self::Body> {
|
||||||
|
match self {
|
||||||
|
ServerError::ValidationError(_) => {
|
||||||
|
let message = format!("Input validation error: [{}]", self).replace("\n", ", ");
|
||||||
|
(StatusCode::BAD_REQUEST, message)
|
||||||
|
}
|
||||||
|
ServerError::AxumFormRejection(_) => (StatusCode::BAD_REQUEST, self.to_string()),
|
||||||
|
}
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user