Skip to content

Commit 2a072d9

Browse files
uckelmanmladedav
authored andcommitted
Add axum_extra::extract::Query::try_from_uri (#3460)
`axum::extract::Query` has a try_from_uri, which is useful for testing. This adds the same function to `axum_extra::extract::Query`.
1 parent 00b5f4c commit 2a072d9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

axum-extra/src/extract/query.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,37 @@ where
126126
}
127127
}
128128

129+
impl<T> Query<T>
130+
where
131+
T: DeserializeOwned,
132+
{
133+
/// Attempts to construct a [`Query`] from a reference to a [`Uri`].
134+
///
135+
/// # Example
136+
/// ```
137+
/// use axum_extra::extract::Query;
138+
/// use http::Uri;
139+
/// use serde::Deserialize;
140+
///
141+
/// #[derive(Deserialize)]
142+
/// struct ExampleParams {
143+
/// foo: String,
144+
/// bar: u32,
145+
/// }
146+
///
147+
/// let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap();
148+
/// let result: Query<ExampleParams> = Query::try_from_uri(&uri).unwrap();
149+
/// assert_eq!(result.foo, String::from("hello"));
150+
/// assert_eq!(result.bar, 42);
151+
/// ```
152+
pub fn try_from_uri(value: &Uri) -> Result<Self, QueryRejection> {
153+
let query = value.query().unwrap_or_default();
154+
let params =
155+
serde_html_form::from_str(query).map_err(FailedToDeserializeQueryString::from_err)?;
156+
Ok(Self(params))
157+
}
158+
}
159+
129160
axum_core::__impl_deref!(Query);
130161

131162
define_rejection! {

0 commit comments

Comments
 (0)