sagebind / isahc

The practical HTTP client that is fun to use.

Home Page:https://docs.rs/isahc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot use Hashmap<String, String> for default_headers

vedantroy opened this issue · comments

I can use a HashMap<&str, &str> for default_headers. But I cannot use HashMap<String, String> . Is there a way to change this?

I guess a follow-up question is why the a HeaderMap requires the keys have a 'static lifetime. This makes inserting headers that are not known at compile-time tricky.

As always -- thanks for making this library!

Thanks for the questions!

I can use a HashMap<&str, &str> for default_headers. But I cannot use HashMap<String, String> . Is there a way to change this?

I believe this is because HeaderName doesn't implement TryFrom<String>, even though it does implement TryFrom<&str> and TryFrom<&String>, which seems a little odd to me and it probably should.

I guess a follow-up question is why the a HeaderMap requires the keys have a 'static lifetime. This makes inserting headers that are not known at compile-time tricky.

This might be a question for the http library, since Isahc just re-exports HeaderMap and other header types from that library. I believe the reason is a balance of header validation at compile time vs. run time. When supplying a &'static str, there's a good chance that the header name is hard-coded so panicking due to invalid headers makes some sense, but for unknown headers panicking isn't appropriate.

By the way, the way to insert unknown header names into a HeaderMap is to first turn your string into a HeaderName using HeaderName::try_from, then giving that to the HeaderMap.

I've opened an upstream issue to add support for this: hyperium/http#479

This is now supported as of http 0.2.5. The following now compiles with the current version of Isahc if you update your transient dependencies via cargo update:

let mut default_headers: HashMap<String, String> = HashMap::new();
default_headers.insert("foo".to_string(), "bar".to_string());

let client = isahc::HttpClient::builder()
    .default_headers(default_headers)
    .build()?;