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::{
|
2022-08-22 12:23:20 +02:00
|
|
|
extract::{rejection::FormRejection, Form, FromRequest},
|
|
|
|
|
http::{Request, StatusCode},
|
2021-12-05 18:16:46 +00:00
|
|
|
response::{Html, IntoResponse, Response},
|
2021-10-24 22:05:16 +02:00
|
|
|
routing::get,
|
2022-08-22 12:23:20 +02:00
|
|
|
Router,
|
2021-09-29 00:12:23 +08:00
|
|
|
};
|
|
|
|
|
use serde::{de::DeserializeOwned, Deserialize};
|
2021-11-28 17:52:18 +00:00
|
|
|
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()
|
2022-11-30 18:46:19 +09:00
|
|
|
.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,
|
2022-08-22 12:23:20 +02:00
|
|
|
Form<T>: FromRequest<S, B, Rejection = FormRejection>,
|
|
|
|
|
B: Send + 'static,
|
2021-09-29 00:12:23 +08:00
|
|
|
{
|
|
|
|
|
type Rejection = ServerError;
|
|
|
|
|
|
2022-08-22 12:23:20 +02:00
|
|
|
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)]
|
2022-08-22 12:23:20 +02:00
|
|
|
AxumFormRejection(#[from] FormRejection),
|
2021-09-29 00:12:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl IntoResponse for ServerError {
|
2021-12-05 18:16:46 +00:00
|
|
|
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()
|
|
|
|
|
}
|
|
|
|
|
}
|