[package]
edition = "2021"
name = "example-validator"
publish = false
version = "0.1.0"
[dependencies]
axum = "0.8.8"
serde = { version = "1.0", features = ["derive"] }
thiserror = "2"
tokio = { version = "1.0", features = ["full"] }
validator = { version = "0.20.0", features = ["derive"] }
[dev-dependencies]
http-body-util = "0.1.0"
tower = { version = "0.5.2", features = ["util"] }
use axum::{
extract::{rejection::FormRejection, Form, FromRequest, Request},
http::StatusCode,
response::{Html, IntoResponse, Response},
routing::get,
Router,
};
use serde::{de::DeserializeOwned, Deserialize};
use thiserror::Error;
use tokio::net::TcpListener;
use validator::Validate;
fn create_router() -> Router {
Router::new()
.route("/", get(handle_main_page))
.route("/echo", get(echo))
}
#[derive(Debug, Deserialize, Validate)]
pub struct TextInput {
#[validate(length(min = 6, message = "Must be at least 6 characters"))]
pub text: String,
}
async fn handle_main_page() -> Html<&'static str> {
Html(
r#"<h1>Echo</h1>
<form method="GET" action="/echo">
<input name="text">
<input type="submit" value="Echo">
</form>
"#,
)
}
async fn echo(ValidatedForm(input): ValidatedForm<TextInput>) -> Html<String> {
Html(format!("<h1>You typed in, <b>{}</b>!</h1>", input.text))
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ValidatedForm<T>(pub T);
impl<T, S> FromRequest<S> for ValidatedForm<T>
where
T: DeserializeOwned + Validate,
S: Send + Sync,
Form<T>: FromRequest<S, Rejection = FormRejection>,
{
type Rejection = ServerError;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let Form(value) = Form::<T>::from_request(req, state).await?;
value.validate()?;
Ok(ValidatedForm(value))
}
}
#[derive(Debug, Error)]
pub enum ServerError {
#[error(transparent)]
ValidationError(#[from] validator::ValidationErrors),
#[error(transparent)]
AxumFormRejection(#[from] FormRejection),
}
impl IntoResponse for ServerError {
fn into_response(self) -> Response {
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()
}
}
#[tokio::main]
async fn main() {
let app = create_router();
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
#[cfg(test)]
mod tests;
#![allow(unused)]
fn main() {
use axum::{
body::Body,
http::{Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
use super::*;
async fn get_html(response: Response<Body>) -> String {
let body = response.into_body();
let bytes = body.collect().await.unwrap().to_bytes();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn test_main_page() {
let response = create_router()
.oneshot(Request::get("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let html = get_html(response).await;
assert!(html.contains("<h1>Echo</h1>"));
assert!(html.contains(r#"<form method="GET" action="/echo">"#));
}
#[tokio::test]
async fn test_no_param() {
let response = create_router()
.oneshot(Request::get("/echo").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let html = get_html(response).await;
assert_eq!(html, "Failed to deserialize form: missing field `text`");
}
#[tokio::test]
async fn test_with_param_without_value() {
let response = create_router()
.oneshot(Request::get("/echo?text=").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let html = get_html(response).await;
assert_eq!(
html,
"Input validation error: [text: Must be at least 6 characters]"
);
}
#[tokio::test]
async fn test_with_param_with_short_value() {
let response = create_router()
.oneshot(
Request::get("/echo?text=short")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let html = get_html(response).await;
assert_eq!(
html,
"Input validation error: [text: Must be at least 6 characters]"
);
}
#[tokio::test]
async fn test_with_param_and_value() {
let response = create_router()
.oneshot(
Request::get("/echo?text=Long+text")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let html = get_html(response).await;
assert_eq!(html, "<h1>You typed in, <b>Long text</b>!</h1>");
}
}