mirror of
https://github.com/fafhrd91/actix-web
synced 2024-11-27 17:52:56 +01:00
Introduce method to set header if it is missing only (#364)
Also let default headers use it. Closes #320
This commit is contained in:
parent
080f232a0f
commit
67e4cad281
@ -421,6 +421,29 @@ impl ClientRequestBuilder {
|
||||
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.
|
||||
///
|
||||
/// 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");
|
||||
|
@ -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"),
|
||||
|
Loading…
Reference in New Issue
Block a user