surf
surf copied to clipboard
Using `http::header::HeaderMap` to create a request
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
- Accessing the internal
http::Request
type doesn't work becausesurf::Request::request()
returns a non-mutable reference. It doesn't seem possible to do what surf does internally (callingself.req.as_mut().unwrap().headers_mut().insert(key, value)
) - Iterating over the
HeaderMap
doesn't seem to work becausesurf::Request::set_header()
expects a&'static str
for the key, but myHeaderMap
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()
?
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).
I feel like for optimal synergy with the Rust ecosystem there should be a way to just use a http::Request.
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.
hyper already takes the Request from the http crate.
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