Название: parse_header.lua module
Отправлено: mirny от 13 февраля 2013, 10:06:07
-- parse_header.lua
local function split(s, delim) local i1 = 1 local ls = {} local append = table.insert if not delim then delim = '%s+' end if delim == '' then return {s} end while true do local i2, i3 = s:find(delim, i1) if not i2 then local last = s:sub(i1) if last ~= '' then append(ls, last) end if #ls == 1 and ls[1] == '' then return {} else return ls end end append(ls, s:sub(i1, i2 - 1)) i1 = i3 + 1 end end
local function parse_header(raw_header) local result = {} local header_entries = split(raw_header:lower(), '\n') for _, header_entry in ipairs(header_entries) do local key, value = header_entry:match'([%w-]+)%s*:%s*(.-)%s*$' if key then result[key:gsub('-', '_')] = value:match'^%d+$' and tonumber(value) or value end end result.code = header_entries[1]:match'(%d%d%d)' return result end
return parse_header
-- parse_header_test.lua
local raw_header = [[ HTTP/1.1 200 OK Server: nginx/1.1.0 Date: Tue, 12 Feb 2013 16:29:16 GMT Content-Type: text/html; charset=WINDOWS-1251 Connection: keep-alive Keep-Alive: timeout=30 X-Powered-By: PHP/5.2.17 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: private Pragma: no-cache Vary: Accept-Encoding Content-Length: 3128 Content-Encoding: gzip Last-Modified: Tue, 12 Feb 2013 16:29:16 GMT
]]
print('-- BEFORE --\n') print(raw_header)
parse_header = require 'parse_header' local header = parse_header(raw_header)
print('-- AFTER --\n')
for k, v in pairs(header) do print('header.' .. k, ' == ', '"' .. v .. '"') end
if header.content_length > 1 then print('\nheader.content_length is a number') end
D:\stuff\test>parse_header_test.lua -- BEFORE --
HTTP/1.1 200 OK Server: nginx/1.1.0 Date: Tue, 12 Feb 2013 16:29:16 GMT Content-Type: text/html; charset=WINDOWS-1251 Connection: keep-alive Keep-Alive: timeout=30 X-Powered-By: PHP/5.2.17 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: private Pragma: no-cache Vary: Accept-Encoding Content-Length: 3128 Content-Encoding: gzip Last-Modified: Tue, 12 Feb 2013 16:29:16 GMT
-- AFTER --
header.connection == "keep-alive" header.content_type == "text/html; charset=windows-1251" header.code == "200" header.date == "tue, 12 feb 2013 16:29:16 gmt" header.keep_alive == "timeout=30" header.x_powered_by == "php/5.2.17" header.expires == "thu, 19 nov 1981 08:52:00 gmt" header.last_modified == "tue, 12 feb 2013 16:29:16 gmt" header.content_encoding == "gzip" header.cache_control == "private" header.content_length == "3128" header.pragma == "no-cache" header.vary == "accept-encoding" header.server == "nginx/1.1.0"
header.content_length is a number
|