Search code examples
rustactix-web

Why is the validator not checked when used for Actix Web query?


I am using Actix Web as my web server, now I want to limit the request parameter length, what I am tried to do like this:

use actix_web::{get, App, HttpResponse, HttpServer, Responder, web};
use validator::Validate;

#[derive(serde::Deserialize, Validate)]
pub struct AppParams {
    #[validate(length(max = 2))]
    tag: String,
}

#[get("/")]
async fn hello(params: web::Query<AppParams>) -> impl Responder {
    HttpResponse::Ok().body("Hello,world!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(hello)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

but when I using this command to check the parameter length in macOS terminal, seems did not work as expect:

> curl http://localhost:8080\?tag\=allallall
Hello,world!%

Am I missing something? What should I do to fixed this issue? This is my Cargo.toml:

[package]
name = "rust-learn"
version = "0.1.0"
edition = "2018"

[dependencies]
tokio = { version = "1.17.0", features = ["full"] }
serde = { version = "1.0.64", features = ["derive"] }
serde_json = "1.0.64"
actix-web = "4"
validator = { version = "0.16.1", features = ["derive"] }

I also tried to add actix-web-validator = "5.0.1" to my dependencies but it still did not work.


Solution

  • You're just using the wrong Query as your parameter type -- you're using actix_web::web::Query<_> but you should use actix_web_validator::Query<_> if you want validation.