Add dynamic custom headers with reqwest

I am trying add custom headers using reqwest. I can't find a suitable option. All the examples quoted online use "static" strings. I need to read the headers from a file and attach to the request.

fn custom_headers(map: &HashMap<String,String>) -> HeaderMap{
    let mut headers = HeaderMap::new();
    for (key, value) in map.iter() {
        headers.insert(HeaderName::from_static(key.as_str()), HeaderValue::from_static(value.as_str()));
    }
    headers
}

Thanks.

You can use the from_bytes constructor for HeaderName and HeaderValue, instead of from_static:

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};

use std::collections::HashMap;

fn custom_headers(map: &HashMap<String,String>) -> HeaderMap {
    let mut headers = HeaderMap::new();
    for (key, value) in map.iter() {
        headers.insert(
            HeaderName::from_bytes(key.as_bytes()).unwrap(), 
            HeaderValue::from_bytes(value.as_bytes()).unwrap(),
        );
    }
    headers
}

Playground.

I guess, I was trying too hard to optimize - by avoiding conversion (String - bytes - str). Guess in the grand scheme of things, the performance doesn't matter much in this case.

If you look at the implementation of the as_bytes method, you'll see that it returns the internal representation of the String, so don't worry about the performance, there is no allocation happening

1 Like