Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added ability to alter headers during the RequestBuilder stage #2546

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/async_impl/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,13 +231,27 @@ impl RequestBuilder {
/// Add a set of Headers to the existing ones on this Request.
///
/// The headers will be merged in to any already set.
/// Headers of the same name will be replaced instead of merged.
pub fn headers(mut self, headers: crate::header::HeaderMap) -> RequestBuilder {
if let Ok(ref mut req) = self.request {
crate::util::replace_headers(req.headers_mut(), headers);
}
self
}

/// Alter existing Headers.
///
/// Does nothing if there was an earlier error when constructing the Request
pub fn alter_headers<F>(mut self, f: F) -> Self
where
F: for<'a> FnOnce(&'a mut HeaderMap),
{
if let Ok(req) = self.request.as_mut() {
(f)(req.headers_mut())
}
self
}

/// Enable HTTP basic authentication.
///
/// ```rust
Expand Down Expand Up @@ -750,6 +764,29 @@ mod tests {
assert_eq!(foo[1], "baz");
}

#[test]
fn test_alter_headers() {
let client = Client::new();
let req = client
.get("https://hyper.rs")
.header("im-a", "keeper")
.header("foo", "pop me")
.alter_headers(|h| {
h.remove("foo");
h.insert("foo", "bar".parse().unwrap());
h.append("foo", "baz".parse().unwrap());
})
.build()
.expect("request build");

assert_eq!(req.headers()["im-a"], "keeper");

let foo = req.headers().get_all("foo").iter().collect::<Vec<_>>();
assert_eq!(foo.len(), 2);
assert_eq!(foo[0], "bar");
assert_eq!(foo[1], "baz");
}

#[test]
fn normalize_empty_query() {
let client = Client::new();
Expand Down