mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-19 00:00:14 +02:00
* Only allow last extractor to mutate the request * Change `FromRequest` and add `FromRequestParts` trait (#1275) * Add `Once`/`Mut` type parameter for `FromRequest` and `RequestParts` * 🪄 * split traits * `FromRequest` for tuples * Remove `BodyAlreadyExtracted` * don't need fully qualified path * don't export `Once` and `Mut` * remove temp tests * depend on axum again Co-authored-by: Jonas Platte <[email protected]> * Port `Handler` and most extractors (#1277) * Port `Handler` and most extractors * Put `M` inside `Handler` impls, not trait itself * comment out tuples for now * fix lints * Reorder arguments to `Handler` (#1281) I think `Request<B>, Arc<S>` is better since its consistent with `FromRequest` and `FromRequestParts`. * Port most things in axum-extra (#1282) * Port `#[derive(TypedPath)]` and `#[debug_handler]` (#1283) * port #[derive(TypedPath)] * wip: #[debug_handler] * fix #[debug_handler] * don't need itertools * also require `Send` * update expected error * support fully qualified `self` * Implement FromRequest[Parts] for tuples (#1286) * Port docs for axum and axum-core (#1285) * Port axum-extra (#1287) * Port axum-extra * Update axum-core/Cargo.toml Co-authored-by: Jonas Platte <[email protected]> * remove `impl FromRequest for Either*` Co-authored-by: Jonas Platte <[email protected]> * New FromRequest[Parts] trait cleanup (#1288) * Make private module truly private again * Simplify tuple FromRequest implementation * Port `#[derive(FromRequest)]` (#1289) * fix tests * fix docs * revert examples * fix docs link * fix intra docs links * Port examples (#1291) * Document wrapping other extractors (#1292) * axum-extra doesn't need to depend on axum-core (#1294) Missed this in https://github.com/tokio-rs/axum/pull/1287 * Add `FromRequest` changes to changelogs (#1293) * Update changelog * Remove default type for `S` in `Handler` * Clarify which types have default types for `S` * Apply suggestions from code review Co-authored-by: Jonas Platte <[email protected]> Co-authored-by: Jonas Platte <[email protected]> * remove unused import * Rename `Mut` and `Once` (#1296) * fix trybuild expected output Co-authored-by: Jonas Platte <[email protected]>
119 lines
3.3 KiB
Rust
119 lines
3.3 KiB
Rust
use axum::{
|
|
async_trait,
|
|
extract::{
|
|
rejection::{FailedToDeserializeQueryString, QueryRejection},
|
|
FromRequestParts,
|
|
},
|
|
};
|
|
use http::request::Parts;
|
|
use serde::de::DeserializeOwned;
|
|
use std::ops::Deref;
|
|
|
|
/// Extractor that deserializes query strings into some type.
|
|
///
|
|
/// `T` is expected to implement [`serde::Deserialize`].
|
|
///
|
|
/// # Differences from `axum::extract::Query`
|
|
///
|
|
/// This extractor uses [`serde_html_form`] under-the-hood which supports multi-value items. These
|
|
/// are sent by multiple `<input>` attributes of the same name (e.g. checkboxes) and `<select>`s
|
|
/// with the `multiple` attribute. Those values can be collected into a `Vec` or other sequential
|
|
/// container.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// ```rust,no_run
|
|
/// use axum::{routing::get, Router};
|
|
/// use axum_extra::extract::Query;
|
|
/// use serde::Deserialize;
|
|
///
|
|
/// #[derive(Deserialize)]
|
|
/// struct Pagination {
|
|
/// page: usize,
|
|
/// per_page: usize,
|
|
/// }
|
|
///
|
|
/// // This will parse query strings like `?page=2&per_page=30` into `Pagination`
|
|
/// // structs.
|
|
/// async fn list_things(pagination: Query<Pagination>) {
|
|
/// let pagination: Pagination = pagination.0;
|
|
///
|
|
/// // ...
|
|
/// }
|
|
///
|
|
/// let app = Router::new().route("/list_things", get(list_things));
|
|
/// # async {
|
|
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
|
|
/// # };
|
|
/// ```
|
|
///
|
|
/// If the query string cannot be parsed it will reject the request with a `422
|
|
/// Unprocessable Entity` response.
|
|
///
|
|
/// For handling values being empty vs missing see the (query-params-with-empty-strings)[example]
|
|
/// example.
|
|
///
|
|
/// [example]: https://github.com/tokio-rs/axum/blob/main/examples/query-params-with-empty-strings/src/main.rs
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "query")))]
|
|
#[derive(Debug, Clone, Copy, Default)]
|
|
pub struct Query<T>(pub T);
|
|
|
|
#[async_trait]
|
|
impl<T, S> FromRequestParts<S> for Query<T>
|
|
where
|
|
T: DeserializeOwned,
|
|
S: Send + Sync,
|
|
{
|
|
type Rejection = QueryRejection;
|
|
|
|
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
|
let query = parts.uri.query().unwrap_or_default();
|
|
let value = serde_html_form::from_str(query)
|
|
.map_err(FailedToDeserializeQueryString::__private_new)?;
|
|
Ok(Query(value))
|
|
}
|
|
}
|
|
|
|
impl<T> Deref for Query<T> {
|
|
type Target = T;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::test_helpers::*;
|
|
use axum::{routing::post, Router};
|
|
use http::{header::CONTENT_TYPE, StatusCode};
|
|
use serde::Deserialize;
|
|
|
|
#[tokio::test]
|
|
async fn supports_multiple_values() {
|
|
#[derive(Deserialize)]
|
|
struct Data {
|
|
#[serde(rename = "value")]
|
|
values: Vec<String>,
|
|
}
|
|
|
|
let app = Router::new().route(
|
|
"/",
|
|
post(|Query(data): Query<Data>| async move { data.values.join(",") }),
|
|
);
|
|
|
|
let client = TestClient::new(app);
|
|
|
|
let res = client
|
|
.post("/?value=one&value=two")
|
|
.header(CONTENT_TYPE, "application/x-www-form-urlencoded")
|
|
.body("")
|
|
.send()
|
|
.await;
|
|
|
|
assert_eq!(res.status(), StatusCode::OK);
|
|
assert_eq!(res.text().await, "one,two");
|
|
}
|
|
}
|