Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Add examples to query #843

Merged
merged 1 commit into from
May 24, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/filters/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,58 @@ use crate::reject::{self, Rejection};
/// 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][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](https://github.com/seanmonstar/warp/blob/master/examples/query_string.rs).
///
/// [Serde]: https://docs.rs/serde
pub fn query<T: DeserializeOwned + Send + 'static>(
) -> impl Filter<Extract = One<T>, Error = Rejection> + Copy {
filter_fn_one(|route| {
Expand Down