heart

Function query

Source
pub fn query<T>() -> impl Filter + Copy
where T: DeserializeOwned + Send + 'static,
Expand description

Creates a Filter that decodes query parameters to the type T.

If cannot decode into a T, the request is rejected with a 400 Bad Request.

ยงExample

use std::collections::HashMap;
use warp::{
    http::Response,
    Filter,
};

let route = warp::any()
    .and(warp::query::<HashMap<String, String>>())
    .map(|map: HashMap<String, String>| {
        let mut response: Vec<String> = Vec::new();
        for (key, value) in map.into_iter() {
            response.push(format!("{}={}", key, value))
        }
        Response::builder().body(response.join(";"))
    });

You can define your custom query object and deserialize with Serde. Ensure to include the crate in your dependencies before usage.

use serde_derive::{Deserialize, Serialize};
use std::collections::HashMap;
use warp::{
    http::Response,
    Filter,
};

#[derive(Serialize, Deserialize)]
struct FooQuery {
    foo: Option<String>,
    bar: u8,
}

let route = warp::any()
    .and(warp::query::<FooQuery>())
    .map(|q: FooQuery| {
        if let Some(foo) = q.foo {
            Response::builder().body(format!("foo={}", foo))
        } else {
            Response::builder().body(format!("bar={}", q.bar))
        }
    });

For more examples, please take a look at examples/query_string.rs.