1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-12-01 02:44:37 +01:00

Merge branch 'master' of github.com:actix/actix-web

This commit is contained in:
Nikolay Kim 2018-07-06 07:49:50 +06:00
commit 2a25caf2c5
2 changed files with 32 additions and 14 deletions

View File

@ -421,6 +421,29 @@ impl ClientRequestBuilder {
self self
} }
/// Set a header only if it is not yet set.
pub fn set_header_if_none<K, V>(&mut self, key: K, value: V) -> &mut Self
where
HeaderName: HttpTryFrom<K>,
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. /// Set content encoding.
/// ///
/// By default `ContentEncoding::Identity` is used. /// By default `ContentEncoding::Identity` is used.
@ -603,22 +626,15 @@ impl ClientRequestBuilder {
}; };
if https { if https {
self.header(header::ACCEPT_ENCODING, "br, gzip, deflate"); self.set_header_if_none(header::ACCEPT_ENCODING, "br, gzip, deflate");
} else { } 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) { self.set_header_if_none(
parts.headers.contains_key(header::USER_AGENT) header::USER_AGENT,
} else { concat!("Actix-web/", env!("CARGO_PKG_VERSION")),
true );
};
if !contains {
self.header(
header::USER_AGENT,
concat!("Actix-web/", env!("CARGO_PKG_VERSION")),
);
}
} }
let mut request = self.request.take().expect("cannot reuse request builder"); let mut request = self.request.take().expect("cannot reuse request builder");

View File

@ -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); let repr_override = format!("{:?}", request_override);
assert!(repr_override.contains("\"user-agent\": \"test\"")); 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!( assert!(!repr_override.contains(concat!(
"\"user-agent\": \"Actix-web/", "\"user-agent\": \"Actix-web/",
env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_VERSION"),