diff --git a/awc/CHANGES.md b/awc/CHANGES.md index 6f8fe2dbd..9b8e27c96 100644 --- a/awc/CHANGES.md +++ b/awc/CHANGES.md @@ -1,5 +1,8 @@ # Changes +## [0.2.8] - 2019-10-24 + +* Add support for setting query from Serialize type for client request. ## [0.2.7] - 2019-09-25 diff --git a/awc/src/request.rs b/awc/src/request.rs index a90cf60b2..6ff68ae66 100644 --- a/awc/src/request.rs +++ b/awc/src/request.rs @@ -382,6 +382,27 @@ impl ClientRequest { } } + /// Sets the query part of the request + pub fn query( + mut self, + query: &T, + ) -> Result { + let mut parts = self.head.uri.clone().into_parts(); + + if let Some(path_and_query) = parts.path_and_query { + let query = serde_urlencoded::to_string(query)?; + let path = path_and_query.path(); + parts.path_and_query = format!("{}?{}", path, query).parse().ok(); + + match Uri::from_parts(parts) { + Ok(uri) => self.head.uri = uri, + Err(e) => self.err = Some(e.into()), + } + } + + Ok(self) + } + /// Freeze request builder and construct `FrozenClientRequest`, /// which could be used for sending same request multiple times. pub fn freeze(self) -> Result { @@ -690,4 +711,13 @@ mod tests { "Bearer someS3cr3tAutht0k3n" ); } + + #[test] + fn client_query() { + let req = Client::new() + .get("/") + .query(&[("key1", "val1"), ("key2", "val2")]) + .unwrap(); + assert_eq!(req.get_uri().query().unwrap(), "key1=val1&key2=val2"); + } }