Skip to content

Commit

Permalink
feat: add functions to return the list of headers of a Response
Browse files Browse the repository at this point in the history
headers() returns a vec of headers of a Response (doing allocations).
headers_iter() returns an iterator over the headers of a Response (no
allocations).
headers_hashmap() returns a hashmap of headers of a Response (doing
allocations).

Signed-off-by: Nils Ponsard <[email protected]>
  • Loading branch information
nponsard committed Jan 15, 2024
1 parent 26ed596 commit d12a893
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,33 @@ impl Response {
.collect()
}

/// Returns a list of all headers in this response.
/// First element of the tuple is the header name, second is the value.
pub fn headers(&self) -> Vec<(String, Option<String>)> {
self.headers
.iter()
.map(|h| (h.name().to_owned(), h.value().map(|v| v.to_owned())))
.collect()
}

/// Iterate over all headers in this response.
/// First element of the tuple is the header name, second is the value.
/// This avoids allocating a vector.
pub fn headers_iter(&self) -> impl Iterator<Item = (&str, Option<&str>)> + '_ {
self.headers.iter().map(|h| (h.name(), h.value()))
}

/// Returns a hashmap of all headers in this response.
/// The keys are the header names, and the values are the header values.
/// Note: if there is multiple entries for the same header name, this function only returns the last one.
pub fn headers_hashmap(&self) -> std::collections::HashMap<String, Option<String>> {
let mut hashmap = std::collections::HashMap::new();
for (key, value) in self.headers_iter() {
hashmap.insert(key.to_string(), value.map(|v| v.to_string()));
}
hashmap
}

/// Tells if the response has the named header.
pub fn has(&self, name: &str) -> bool {
self.header(name).is_some()
Expand Down

0 comments on commit d12a893

Please sign in to comment.