Add name_eq method on Header.

This commit is contained in:
jcamiel 2024-02-15 18:21:51 +01:00
parent 09266c9581
commit 42dd0c1643
No known key found for this signature in database
GPG Key ID: 07FF11CFD55356CC
3 changed files with 14 additions and 15 deletions

View File

@ -133,9 +133,7 @@ impl Client {
let headers = if options.follow_location_trusted {
request_spec.headers
} else {
request_spec
.headers
.retain(|h| h.name.to_lowercase() != AUTHORIZATION.to_lowercase());
request_spec.headers.retain(|h| !h.name_eq(AUTHORIZATION));
request_spec.headers
};
request_spec = RequestSpec {

View File

@ -42,12 +42,20 @@ impl fmt::Display for Header {
}
impl Header {
/// Creates an HTTP header with this `name`and `value`.
pub fn new(name: &str, value: &str) -> Self {
Header {
name: name.to_string(),
value: value.to_string(),
}
}
/// Returns `true` if this HTTP header name is equal to `name`.
///
/// An HTTP header consists of a case-insensitive name.
pub fn name_eq(&self, name: &str) -> bool {
self.name.to_lowercase() == name.to_lowercase()
}
}
/// Represents an ordered list of [`Header`].
@ -68,24 +76,17 @@ impl HeaderVec {
/// If there are multiple headers associated with `name`, then the first one is returned.
/// Use [`get_all`] to get all values associated with a given key.
pub fn get(&self, name: &str) -> Option<&Header> {
self.headers
.iter()
.find(|h| h.name.to_lowercase() == name.to_lowercase())
self.headers.iter().find(|h| h.name_eq(name))
}
/// Returns a list of header associated with `name`.
pub fn get_all(&self, name: &str) -> Vec<&Header> {
self.headers
.iter()
.filter(|h| h.name.to_lowercase() == name.to_lowercase())
.collect()
self.headers.iter().filter(|h| h.name_eq(name)).collect()
}
/// Returns true if there is at least one header with the specified `name`.
pub fn contains_key(&self, name: &str) -> bool {
self.headers
.iter()
.any(|h| h.name.to_lowercase() == name.to_lowercase())
self.headers.iter().any(|h| h.name_eq(name))
}
/// Retains only the header specified by the predicate.
@ -173,7 +174,7 @@ mod tests {
assert!(headers.contains_key("FOO"));
assert!(!headers.contains_key("fuu"));
headers.retain(|h| h.name.to_lowercase() == "bar");
headers.retain(|h| h.name_eq("Bar"));
assert_eq!(headers.len(), 3);
}

View File

@ -48,7 +48,7 @@ impl HeaderVec {
/// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
pub fn content_encoding(&self) -> Result<Vec<ContentEncoding>, HttpError> {
for header in self {
if header.name.to_lowercase() == CONTENT_ENCODING.to_lowercase() {
if header.name_eq(CONTENT_ENCODING) {
let mut encodings = vec![];
for value in header.value.split(',') {
let encoding = ContentEncoding::parse(value.trim())?;