2 -- Copyright (C) 2013 Florian Zeitz
4 -- This project is MIT/X11 licensed. Please see the
5 -- COPYING file in the source package for more information.
8 local format, char
= string.format, string.char
;
9 local pairs
, ipairs
= pairs
, ipairs
;
10 local t_insert
, t_concat
= table.insert
, table.concat
;
15 local u
= format("%%%02x", i
);
18 url_codes
[u
:upper()] = c
;
20 local function urlencode(s
)
21 return s
and (s
:gsub("[^a-zA-Z0-9.~_-]", url_codes
));
23 local function urldecode(s
)
24 return s
and (s
:gsub("%%%x%x", url_codes
));
27 local function _formencodepart(s
)
28 return s
and (urlencode(s
):gsub("%%20", "+"));
31 local function formencode(form
)
33 if form
[1] then -- Array of ordered { name, value }
34 for _
, field
in ipairs(form
) do
35 t_insert(result
, _formencodepart(field
.name
).."=".._formencodepart(field
.value
));
37 else -- Unordered map of name -> value
38 for name
, value
in pairs(form
) do
39 t_insert(result
, _formencodepart(name
).."=".._formencodepart(value
));
42 return t_concat(result
, "&");
45 local function formdecode(s
)
46 if not s
:match("=") then return urldecode(s
); end
48 for k
, v
in s
:gmatch("([^=&]*)=([^&]*)") do
49 k
, v
= k
:gsub("%+", "%%20"), v
:gsub("%+", "%%20");
50 k
, v
= urldecode(k
), urldecode(v
);
51 t_insert(r
, { name
= k
, value
= v
});
57 local function contains_token(field
, token
)
58 field
= ","..field
:gsub("[ \t]", ""):lower()..",";
59 return field
:find(","..token
:lower()..",", 1, true) ~= nil;
62 local function normalize_path(path
, is_dir
)
64 if path
:sub(-1,-1) ~= "/" then path
= path
.."/"; end
66 if path
:sub(-1,-1) == "/" then path
= path
:sub(1, -2); end
68 if path
:sub(1,1) ~= "/" then path
= "/"..path
; end
73 urlencode
= urlencode
, urldecode
= urldecode
;
74 formencode
= formencode
, formdecode
= formdecode
;
75 contains_token
= contains_token
;
76 normalize_path
= normalize_path
;