From f0612f757001dde1509892f386d5d3033194f540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathas=20Concei=C3=A7=C3=A3o?= Date: Sat, 26 Oct 2019 02:27:14 -0300 Subject: [PATCH] awc: Add support for setting query from Serialize type for client request (#1130) Signed-off-by: Jonathas-Conceicao --- awc/CHANGES.md | 3 +++ awc/src/request.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/awc/CHANGES.md b/awc/CHANGES.md index 6f8fe2db..9b8e27c9 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 a90cf60b..6ff68ae6 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"); + } }