msb protocol synch change
[msb/apigateway.git] / msb-core / openresty-ext / src / assembly / resources / openresty / lualib / resty / http_headers.lua
1 local   rawget, rawset, setmetatable =
2         rawget, rawset, setmetatable
3
4 local str_gsub = string.gsub
5 local str_lower = string.lower
6
7
8 local _M = {
9     _VERSION = '0.01',
10 }
11
12
13 -- Returns an empty headers table with internalised case normalisation.
14 -- Supports the same cases as in ngx_lua:
15 --
16 -- headers.content_length
17 -- headers["content-length"]
18 -- headers["Content-Length"]
19 function _M.new(self)
20     local mt = { 
21         normalised = {},
22     }
23
24
25     mt.__index = function(t, k)
26         local k_hyphened = str_gsub(k, "_", "-")
27         local matched = rawget(t, k)
28         if matched then
29             return matched
30         else
31             local k_normalised = str_lower(k_hyphened)
32             return rawget(t, mt.normalised[k_normalised])
33         end
34     end
35
36
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().
43     mt.__newindex = function(t, k, 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
56     end
57
58     return setmetatable({}, mt)
59 end
60
61
62 return _M