Skip to content

Commit 6e2eeef

Browse files
committed
Default to empty string when query string is missing
1 parent 9fa2a16 commit 6e2eeef

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

src/request.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::headers::{
1414
};
1515
use crate::mime::Mime;
1616
use crate::trailers::{self, Trailers};
17-
use crate::{Body, Extensions, Method, Url, Version};
17+
use crate::{Body, Extensions, Method, StatusCode, Url, Version};
1818

1919
pin_project_lite::pin_project! {
2020
/// An HTTP request.
@@ -627,12 +627,15 @@ impl Request {
627627
/// # Ok(()) }
628628
/// ```
629629
pub fn query<T: serde::de::DeserializeOwned>(&self) -> crate::Result<T> {
630-
use std::io::{Error, ErrorKind};
631-
let query = self
632-
.url
633-
.query()
634-
.ok_or_else(|| Error::from(ErrorKind::InvalidData))?;
635-
Ok(serde_urlencoded::from_str(query)?)
630+
// Default to an empty query string if no query parameter has been specified.
631+
// This allows successful deserialisation of structs where all fields are optional
632+
// when none of those fields has actually been passed by the caller.
633+
let query = self.url().query().unwrap_or("");
634+
serde_urlencoded::from_str(query).map_err(|e| {
635+
// Return the displayable version of the deserialisation error to the caller
636+
// for easier debugging.
637+
crate::Error::from_str(StatusCode::BadRequest, format!("{}", e))
638+
})
636639
}
637640

638641
/// Set the URL querystring.

tests/querystring.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ fn unsuccessfully_deserialize_query() {
3030

3131
let params = req.query::<Params>();
3232
assert!(params.is_err());
33-
assert_eq!(params.err().unwrap().to_string(), "invalid data");
33+
assert_eq!(params.err().unwrap().to_string(), "missing field `msg`");
3434
}
3535

3636
#[test]

0 commit comments

Comments
 (0)