CodexBloom - Programming Q&A Platform

Difficulty with implementing a custom HTTP client using `reqwest` in Rust with dynamic headers

👀 Views: 409 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
rust reqwest http Rust

I'm stuck on something that should probably be simple. I'm trying to create a custom HTTP client using the `reqwest` library in Rust that needs to set dynamic headers based on user input. However, I am running into issues when trying to add headers to my requests. Even though I am following the documentation, I keep getting the following behavior message: ``` thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Header(InvalidHeader) ``` The behavior suggests that the header I'm trying to set is invalid, but I need to quite figure out what I'm doing wrong. Here's a simplified version of my code: ```rust use reqwest::{Client, header::{HeaderMap, HeaderValue}}; fn create_client(headers: Vec<(&str, &str)>) -> Result<Client, reqwest::behavior> { let client = Client::new(); let mut header_map = HeaderMap::new(); for (key, value) in headers { let header_value = HeaderValue::from_str(value).expect("Invalid header value"); header_map.insert(key, header_value); } client.request(reqwest::Method::GET, "https://httpbin.org/get") .headers(header_map) .send()?; Ok(client) } fn main() { let headers = vec![ ("User-Agent", "my-custom-client"), ("Content-Type", "application/json") ]; let client = create_client(headers); match client { Ok(_) => println!("Client created successfully"), Err(e) => eprintln!("behavior creating client: {}", e), } } ``` When I run this code, the client creation fails due to the invalid header behavior. I've double-checked the header names and values, and they should be valid according to the HTTP spec. I'm using `reqwest` version `0.11.3`. Could anyone guide to understand what might be going wrong? Are there specific rules for header names or values that I might be overlooking? What am I doing wrong?