Extract Responses header conversion into a shared module (#48200)

Move JSON-to-HTTP header conversion from `responses_websocket` into the
crate-wide `responses_headers` module and update the WebSocket code to use it.
Preserve conversion of string, number, and boolean values, while continuing to
ignore invalid header names and unsupported or invalid values.

GitOrigin-RevId: f179de214cf763549b5b8a898dc4bcda3ce07ebd
This commit is contained in:
Adam Perry @ OpenAI
2026-09-25 20:12:54 +00:00
committed by copyberry
parent 7596ab19a6
commit dd9a7101d9
3 changed files with 35 additions and 26 deletions
@@ -0,0 +1,32 @@
//! Converts headers in Responses event payloads to HTTP headers.
//! Invalid names and unsupported or invalid values are ignored.
use http::HeaderMap;
use http::HeaderName;
use http::HeaderValue;
use serde_json::Value;
use serde_json::map::Map as JsonMap;
pub(crate) fn json_headers_to_http_headers(headers: &JsonMap<String, Value>) -> HeaderMap {
let mut mapped = HeaderMap::new();
for (name, value) in headers {
let Ok(header_name) = HeaderName::from_bytes(name.as_bytes()) else {
continue;
};
let Some(header_value) = json_header_value(value) else {
continue;
};
mapped.insert(header_name, header_value);
}
mapped
}
fn json_header_value(value: &Value) -> Option<HeaderValue> {
let value = match value {
Value::String(value) => value.clone(),
Value::Number(value) => value.to_string(),
Value::Bool(value) => value.to_string(),
_ => return None,
};
HeaderValue::from_str(&value).ok()
}