Mercurial > prosody-hg
comparison util/http.lua @ 5458:84162b81c863
net.http, util.http: Move definitions of urlencode/decode and formencode/decode to util.http (possible to use them without unnecessary network-related dependencies)
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Thu, 11 Apr 2013 17:32:59 +0100 |
| parents | cc9d460aa779 |
| children | 34bfd26525f5 |
comparison
equal
deleted
inserted
replaced
| 5454:5f69fddf6fb9 | 5458:84162b81c863 |
|---|---|
| 5 -- COPYING file in the source package for more information. | 5 -- COPYING file in the source package for more information. |
| 6 -- | 6 -- |
| 7 | 7 |
| 8 local http = {}; | 8 local http = {}; |
| 9 | 9 |
| 10 function http.urlencode(s) | |
| 11 return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return format("%%%02x", c:byte()); end)); | |
| 12 end | |
| 13 function http.urldecode(s) | |
| 14 return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); | |
| 15 end | |
| 16 | |
| 17 local function _formencodepart(s) | |
| 18 return s and (s:gsub("%W", function (c) | |
| 19 if c ~= " " then | |
| 20 return format("%%%02x", c:byte()); | |
| 21 else | |
| 22 return "+"; | |
| 23 end | |
| 24 end)); | |
| 25 end | |
| 26 | |
| 27 function http.formencode(form) | |
| 28 local result = {}; | |
| 29 if form[1] then -- Array of ordered { name, value } | |
| 30 for _, field in ipairs(form) do | |
| 31 t_insert(result, _formencodepart(field.name).."=".._formencodepart(field.value)); | |
| 32 end | |
| 33 else -- Unordered map of name -> value | |
| 34 for name, value in pairs(form) do | |
| 35 t_insert(result, _formencodepart(name).."=".._formencodepart(value)); | |
| 36 end | |
| 37 end | |
| 38 return t_concat(result, "&"); | |
| 39 end | |
| 40 | |
| 41 function http.formdecode(s) | |
| 42 if not s:match("=") then return urldecode(s); end | |
| 43 local r = {}; | |
| 44 for k, v in s:gmatch("([^=&]*)=([^&]*)") do | |
| 45 k, v = k:gsub("%+", "%%20"), v:gsub("%+", "%%20"); | |
| 46 k, v = urldecode(k), urldecode(v); | |
| 47 t_insert(r, { name = k, value = v }); | |
| 48 r[k] = v; | |
| 49 end | |
| 50 return r; | |
| 51 end | |
| 52 | |
| 10 function http.contains_token(field, token) | 53 function http.contains_token(field, token) |
| 11 field = ","..field:gsub("[ \t]", ""):lower()..","; | 54 field = ","..field:gsub("[ \t]", ""):lower()..","; |
| 12 return field:find(","..token:lower()..",", 1, true) ~= nil; | 55 return field:find(","..token:lower()..",", 1, true) ~= nil; |
| 13 end | 56 end |
| 14 | 57 |
| 58 | |
| 59 | |
| 15 return http; | 60 return http; |
