Skip to content

feat: restore header case-insensitivity #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions __test__/handler.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,9 @@ test('Support request and response headers', async (t) => {
'index.php': `<?php
$headers = apache_request_headers();
header("X-Test: Hello, from PHP!");
// TODO: Does PHP expect headers be returned to uppercase?
echo $headers["X-Test"];
// apache_request_headers is specified to contain whichever casing was
// received from the client, so just use lang_handler's lowercase value.
echo $headers["x-test"];
?>`
})
t.teardown(() => mockroot.clean())
Expand Down
10 changes: 5 additions & 5 deletions __test__/headers.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ test('includes iterator methods', (t) => {
const entries = Array.from(headers.entries())
.sort((a, b) => a[0].localeCompare(b[0]))
t.deepEqual(entries, [
['Accept', 'application/json'],
['Content-Type', 'application/json']
['accept', 'application/json'],
['content-type', 'application/json']
])

const keys = Array.from(headers.keys()).sort()
t.deepEqual(keys, ['Accept', 'Content-Type'])
t.deepEqual(keys, ['accept', 'content-type'])

const values = Array.from(headers.values()).sort()
t.deepEqual(values, ['application/json', 'application/json'])
Expand All @@ -77,7 +77,7 @@ test('includes iterator methods', (t) => {
seen.push([name, values, map])
})
t.deepEqual(seen.sort((a, b) => a[0].localeCompare(b[0])), [
['Accept', 'application/json', headers],
['Content-Type', 'application/json', headers]
['accept', 'application/json', headers],
['content-type', 'application/json', headers]
])
})
44 changes: 23 additions & 21 deletions crates/lang_handler/src/headers.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::{hash_map::Entry, HashMap};

/// Represents a single HTTP header value or multiple values for the same header.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Header {
/// A single value for a header.
Single(String),
Expand Down Expand Up @@ -62,9 +62,7 @@ impl Headers {
where
K: AsRef<str>,
{
self
.0
.contains_key(key.as_ref() /*.to_lowercase().as_str()*/)
self.0.contains_key(key.as_ref().to_lowercase().as_str())
}

/// Returns the last single value associated with a header field.
Expand All @@ -83,7 +81,7 @@ impl Headers {
where
K: AsRef<str>,
{
match self.0.get(key.as_ref() /*.to_lowercase().as_str()*/) {
match self.0.get(key.as_ref().to_lowercase().as_str()) {
Some(Header::Single(value)) => Some(value.clone()),
Some(Header::Multiple(values)) => values.last().cloned(),
None => None,
Expand Down Expand Up @@ -112,7 +110,7 @@ impl Headers {
where
K: AsRef<str>,
{
match self.0.get(key.as_ref() /*.to_lowercase().as_str()*/) {
match self.0.get(key.as_ref().to_lowercase().as_str()) {
Some(Header::Single(value)) => vec![value.clone()],
Some(Header::Multiple(values)) => values.clone(),
None => Vec::new(),
Expand Down Expand Up @@ -143,12 +141,10 @@ impl Headers {
where
K: AsRef<str>,
{
let result = self.get_all(key).join(",");
if result.is_empty() {
None
} else {
Some(result)
}
self
.0
.get(key.as_ref().to_lowercase().as_str())
.map(|v| v.into())
}

/// Sets a header field, replacing any existing values.
Expand All @@ -168,10 +164,9 @@ impl Headers {
K: Into<String>,
V: Into<String>,
{
self.0.insert(
key.into(), /*.to_lowercase()*/
Header::Single(value.into()),
);
self
.0
.insert(key.into().to_lowercase(), Header::Single(value.into()));
}

/// Add a header with the given value without replacing existing ones.
Expand All @@ -194,7 +189,7 @@ impl Headers {
K: Into<String>,
V: Into<String>,
{
let key = key.into()/*.to_lowercase()*/;
let key = key.into().to_lowercase();
let value = value.into();

match self.0.entry(key) {
Expand Down Expand Up @@ -234,7 +229,7 @@ impl Headers {
where
K: AsRef<str>,
{
self.0.remove(key.as_ref() /*.to_lowercase().as_str()*/);
self.0.remove(key.as_ref().to_lowercase().as_str());
}

/// Clears all headers.
Expand Down Expand Up @@ -292,14 +287,21 @@ impl Headers {
/// # Examples
///
/// ```
/// # use lang_handler::Headers;
/// # use lang_handler::{Headers, Header};
/// let mut headers = Headers::new();
/// headers.set("Accept", "text/plain");
/// headers.set("Accept", "application/json");
/// headers.add("Accept", "text/plain");
/// headers.add("Accept", "application/json");
///
/// for (key, values) in headers.iter() {
/// println!("{}: {:?}", key, values);
/// }
///
/// # assert_eq!(headers.iter().collect::<Vec<(&String, &Header)>>(), vec![
/// # (&"accept".to_string(), &Header::Multiple(vec![
/// # "text/plain".to_string(),
/// # "application/json".to_string()
/// # ]))
/// # ]);
/// ```
pub fn iter(&self) -> impl Iterator<Item = (&String, &Header)> {
self.0.iter()
Expand Down
15 changes: 4 additions & 11 deletions crates/php/src/sapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ use ext_php_rs::{
use once_cell::sync::OnceCell;

use crate::{EmbedRequestError, EmbedStartError, RequestContext};
use lang_handler::Header;

// This is a helper to ensure that PHP is initialized and deinitialized at the
// appropriate times.
Expand Down Expand Up @@ -381,16 +380,10 @@ pub extern "C" fn sapi_module_register_server_variables(vars: *mut ext_php_rs::t
Ok::<(), EmbedRequestError>(())
.and_then(|_| {
for (key, values) in headers.iter() {
let maybe_header = match values {
Header::Single(header) => Some(header),
Header::Multiple(headers) => headers.first(),
};

if let Some(header) = maybe_header {
let upper = key.to_ascii_uppercase();
let cgi_key = format!("HTTP_{}", upper.replace("-", "_"));
env_var(vars, cgi_key, header)?;
}
let value_string: String = values.into();
let upper = key.to_ascii_uppercase();
let cgi_key = format!("HTTP_{}", upper.replace("-", "_"));
env_var(vars, cgi_key, value_string)?;
}

let globals = SapiGlobals::get();
Expand Down
Loading