Files
axum/examples/validator/src/main.rs
T

101 lines
2.7 KiB
Rust
Raw Normal View History

2021-09-29 00:12:23 +08:00
//! Run with
//!
//! ```not_rust
2022-04-29 18:53:41 +02:00
//! cd examples && cargo run -p example-validator
2021-09-29 00:12:23 +08:00
//!
//! 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::{
extract::{rejection::FormRejection, Form, FromRequest},
http::{Request, StatusCode},
response::{Html, IntoResponse, Response},
routing::get,
Router,
2021-09-29 00:12:23 +08:00
};
use serde::{de::DeserializeOwned, Deserialize};
use std::net::SocketAddr;
2021-09-29 00:12:23 +08:00
use thiserror::Error;
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-09-29 00:12:23 +08:00
use validator::Validate;
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_validator=debug".into()),
)
2022-03-06 12:37:00 +01:00
.with(tracing_subscriber::fmt::layer())
.init();
2021-09-29 00:12:23 +08:00
// 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]
2022-08-17 17:13:31 +02:00
impl<T, S, B> FromRequest<S, B> for ValidatedForm<T>
2021-09-29 00:12:23 +08:00
where
T: DeserializeOwned + Validate,
2022-08-17 22:08:24 +02:00
S: Send + Sync,
Form<T>: FromRequest<S, B, Rejection = FormRejection>,
B: Send + 'static,
2021-09-29 00:12:23 +08:00
{
type Rejection = ServerError;
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let Form(value) = Form::<T>::from_request(req, state).await?;
2021-09-29 00:12:23 +08:00
value.validate()?;
Ok(ValidatedForm(value))
}
}
#[derive(Debug, Error)]
pub enum ServerError {
#[error(transparent)]
ValidationError(#[from] validator::ValidationErrors),
#[error(transparent)]
AxumFormRejection(#[from] FormRejection),
2021-09-29 00:12:23 +08:00
}
impl IntoResponse for ServerError {
fn into_response(self) -> Response {
2021-09-29 00:12:23 +08:00
match self {
ServerError::ValidationError(_) => {
2021-12-12 17:21:29 +01:00
let message = format!("Input validation error: [{}]", self).replace('\n', ", ");
2021-09-29 00:12:23 +08:00
(StatusCode::BAD_REQUEST, message)
}
ServerError::AxumFormRejection(_) => (StatusCode::BAD_REQUEST, self.to_string()),
}
.into_response()
}
}