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
Implement TryFrom<HashMap<String, String>> for HeaderMap #555
Comments
You can just do something like use std::collections::HashMap;
use std::str::FromStr;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
fn headermap_from_hashmap<'a, I, S>(headers: I) -> HeaderMap
where
I: Iterator<Item = (S, S)> + 'a,
S: AsRef<str> + 'a,
{
headers
.map(|(name, val)| (HeaderName::from_str(name.as_ref()), HeaderValue::from_str(val.as_ref())))
// We ignore the errors here. If you want to get a list of failed conversions, you can use Iterator::partition
// to help you out here
.filter(|(k, v)| k.is_ok() && v.is_ok())
.map(|(k, v)| (k.unwrap(), v.unwrap()))
.collect()
}
fn main() {
let hashmap: HashMap<String, String> = [("x-test", "foobar"), ("x-testing", "bar")]
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
println!("{:#?}", headermap_from_hashmap(hashmap.iter()));
} Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=831e89334756b899d2dc61950795789e |
Yes, this is what I do currently. But this is not very ergonomic. Especially if you want to add error handling. Don't you think |
I agree it's rather unergonomic. Anyway, the various I think this requires a bump of the minimum Rust version to |
No, this is not needed, because they already implement |
Sure. Another complication is that |
I also made a pull request to the http crate: hyperium/http#326 |
hyperium/http#326 is now merged |
Any updates on this? |
Looks like the work from hyperium/http#326 got removed from the http crate at some point. Looks like you can use TryFrom now. @lovasoa Does this resolve this issue? Maybe you can close it if so? |
Yes, feel free to close if this has been solved, this is an old issue. |
Currently, reqwest provides no easy way to use a HashMap of strings as headers, and converting from a HashMap to a HeaderMap is not straightforward.
Converting from a String to a
HeaderName
can return an InvalidHeaderName, and converting from a string to aHeaderValue
can return a different type of error (InvalidHeaderValue). Andreqwest::Error
does not implementFrom<_>
for these error types, which makes it impossible to use the?
operator.It would be nice to be able to write a simple
Instead of having to write a verbose conversion function that handles error type conversions.
The conversion implementation could even be generic, so that it would work with any
IntoIterator<(ToString, ToString)>
The text was updated successfully, but these errors were encountered: