surf icon indicating copy to clipboard operation
surf copied to clipboard

Using `http::header::HeaderMap` to create a request

Open codehearts opened this issue 5 years ago • 5 comments

I currently have an http::header::HeaderMap that I want to use with my surf request, but I'm having a lot of trouble getting this to work. I tried a few approaches, but for one reason or another they just aren't feasible

  1. Accessing the internal http::Request type doesn't work because surf::Request::request() returns a non-mutable reference. It doesn't seem possible to do what surf does internally (calling self.req.as_mut().unwrap().headers_mut().insert(key, value))
  2. Iterating over the HeaderMap doesn't seem to work because surf::Request::set_header() expects a &'static str for the key, but my HeaderMap has a non-static lifetime

Are there any suggestions on how this could be addressed? I could use a different type in place of HeaderMap, but I want to avoid this because surf will panic if the header value does not parse cleanly

It seems like surf deliberately lacks this API because it's more complicated than the current set_header API (I totally agree), but would it be possible to maybe add a surf::Request::request_mut() or surf::Request::set_headers_from_map()?

codehearts avatar Nov 27 '19 23:11 codehearts

Having the same issue at the moment. The &'static str requirement for set_header() prevents use cases where the header is actually dynamically put together (not from static str).

nhellwig avatar Dec 02 '19 13:12 nhellwig

I feel like for optimal synergy with the Rust ecosystem there should be a way to just use a http::Request.

CryZe avatar Dec 02 '19 13:12 CryZe

Just create a very small pull-request that will make the set_header method a little bit more flexible in terms of headers accepted. But you are right @CryZe ultimately I favour a standard http::Request. Not sure how this might work with hyper client. But really do not have enough insight here.

nhellwig avatar Dec 02 '19 14:12 nhellwig

hyper already takes the Request from the http crate.

CryZe avatar Dec 02 '19 14:12 CryZe

Making the key non-static helps a lot, thanks! In my case I'll still have to unwrap my HeaderValues into &str only to be converted back to HeaderValues again

It might be convenient to also take a impl Into<HeaderValue> as the value and maybe add a set_headers() to take an iterator and see each header. I may not get around to this since surf's use of unwrap rather than ? isn't suitable for my use cases

codehearts avatar Dec 02 '19 19:12 codehearts