Skip to content

Commit 170d699

Browse files
committed
Third time lucky with metatable logic. We now ensure our header fields are unique
1 parent eadf395 commit 170d699

File tree

3 files changed

+47
-6
lines changed

3 files changed

+47
-6
lines changed

lib/resty/http.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ end
6666

6767

6868
local _M = {
69-
_VERSION = '0.04',
69+
_VERSION = '0.05',
7070
}
7171

7272
local mt = { __index = _M }

lib/resty/http_headers.lua

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,30 @@ function _M.new(self)
2929
return matched
3030
else
3131
local k_normalised = str_lower(k_hyphened)
32-
return rawget(mt.normalised, k_normalised)
32+
return rawget(t, mt.normalised[k_normalised])
3333
end
3434
end
3535

3636

37+
-- First check the normalised table. If there's no match (first time) add an entry for
38+
-- our current case in the normalised table. This is to preserve the human (prettier) case
39+
-- instead of outputting lowercased header names.
40+
--
41+
-- If there's a match, we're being updated, just with a different case for the key. We use
42+
-- the normalised table to give us the original key, and perorm a rawset().
3743
mt.__newindex = function(t, k, v)
38-
local k_hyphened = str_gsub(k, "_", "-")
39-
local k_normalised = str_lower(k_hyphened)
40-
rawset(mt.normalised, k_normalised, v)
41-
rawset(t, k_hyphened, v)
44+
-- we support underscore syntax, so always hyphenate.
45+
local k_hyphened = str_gsub(k, "_", "-")
46+
47+
-- lowercase hyphenated is "normalised"
48+
local k_normalised = str_lower(k_hyphened)
49+
50+
if not mt.normalised[k_normalised] then
51+
mt.normalised[k_normalised] = k_hyphened
52+
rawset(t, k_hyphened, v)
53+
else
54+
rawset(t, mt.normalised[k_normalised], v)
55+
end
4256
end
4357

4458
return setmetatable({}, mt)

t/12-case_insensitive_headers.t

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,31 @@ test_user_agent
130130
bar
131131
--- no_error_log
132132
[error]
133+
134+
135+
=== TEST 4: Test that headers remain unique
136+
--- http_config eval: $::HttpConfig
137+
--- config
138+
location = /a {
139+
content_by_lua '
140+
local http_headers = require "resty.http_headers"
141+
142+
local headers = http_headers.new()
143+
144+
headers["x-a-header"] = "a"
145+
headers["X-A-HEAder"] = "b"
146+
147+
for k,v in pairs(headers) do
148+
ngx.log(ngx.DEBUG, k, ": ", v)
149+
ngx.header[k] = v
150+
end
151+
';
152+
}
153+
--- request
154+
GET /a
155+
--- response_headers
156+
x-a-header: b
157+
--- no_error_log
158+
[error]
159+
[warn]
133160
[warn]

0 commit comments

Comments
 (0)