From 67e4cad2819ab9c57632172d75b9c4262dad6c33 Mon Sep 17 00:00:00 2001 From: Douman Date: Thu, 5 Jul 2018 19:27:18 +0300 Subject: [PATCH] Introduce method to set header if it is missing only (#364) Also let default headers use it. Closes #320 --- src/client/request.rs | 42 +++++++++++++++++++++++++++++------------- tests/test_client.rs | 4 +++- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/src/client/request.rs b/src/client/request.rs index 351b4b6df..ef058373b 100644 --- a/src/client/request.rs +++ b/src/client/request.rs @@ -421,6 +421,29 @@ impl ClientRequestBuilder { self } + /// Set a header only if it is not yet set. + pub fn set_header_if_none(&mut self, key: K, value: V) -> &mut Self + where + HeaderName: HttpTryFrom, + V: IntoHeaderValue, + { + if let Some(parts) = parts(&mut self.request, &self.err) { + match HeaderName::try_from(key) { + Ok(key) => match parts.headers.contains_key(&key) { + false => match value.try_into() { + Ok(value) => { + parts.headers.insert(key, value); + } + Err(e) => self.err = Some(e.into()), + }, + true => (), + }, + Err(e) => self.err = Some(e.into()), + }; + } + self + } + /// Set content encoding. /// /// By default `ContentEncoding::Identity` is used. @@ -603,22 +626,15 @@ impl ClientRequestBuilder { }; if https { - self.header(header::ACCEPT_ENCODING, "br, gzip, deflate"); + self.set_header_if_none(header::ACCEPT_ENCODING, "br, gzip, deflate"); } else { - self.header(header::ACCEPT_ENCODING, "gzip, deflate"); + self.set_header_if_none(header::ACCEPT_ENCODING, "gzip, deflate"); } - let contains = if let Some(parts) = parts(&mut self.request, &self.err) { - parts.headers.contains_key(header::USER_AGENT) - } else { - true - }; - if !contains { - self.header( - header::USER_AGENT, - concat!("Actix-web/", env!("CARGO_PKG_VERSION")), - ); - } + self.set_header_if_none( + header::USER_AGENT, + concat!("Actix-web/", env!("CARGO_PKG_VERSION")), + ); } let mut request = self.request.take().expect("cannot reuse request builder"); diff --git a/tests/test_client.rs b/tests/test_client.rs index c4575c878..d128fa310 100644 --- a/tests/test_client.rs +++ b/tests/test_client.rs @@ -443,9 +443,11 @@ fn test_default_headers() { "\"" ))); - let request_override = srv.get().header("User-Agent", "test").finish().unwrap(); + let request_override = srv.get().header("User-Agent", "test").header("Accept-Encoding", "over_test").finish().unwrap(); let repr_override = format!("{:?}", request_override); assert!(repr_override.contains("\"user-agent\": \"test\"")); + assert!(repr_override.contains("\"accept-encoding\": \"over_test\"")); + assert!(!repr_override.contains("\"accept-encoding\": \"gzip, deflate\"")); assert!(!repr_override.contains(concat!( "\"user-agent\": \"Actix-web/", env!("CARGO_PKG_VERSION"),