This CGI module is way better

This commit is contained in:
Neale Pickett 2015-04-18 14:24:00 -06:00
parent f81fa989c9
commit af2bc9bc8d
2 changed files with 46 additions and 43 deletions

View File

@ -26,17 +26,30 @@ function getc_get()
end end
end end
function cgi.http_error(code, name, info) function read_hex()
print(code .. " " .. name) local a = getc() or 0
print("Allow: GET POST") local b = getc() or 0
print("Content-type: text/html")
print() return string.char(tonumber(a, 16)*16 + tonumber(b, 16))
print("<h1>" .. code .. " " .. name .. "</h1>")
print("<p>" .. info .. "</p>")
os.exit(0)
end end
function cgi.init() function item()
local val = ""
while (true) do
local c = getc()
if ((c == nil) or (c == "=") or (c == "&")) then
return val
elseif (c == "%") then
c = read_hex()
elseif (c == "+") then
c = " "
end
val = val .. c
end
end
function init()
method = os.getenv("REQUEST_METHOD") method = os.getenv("REQUEST_METHOD")
if (method == "POST") then if (method == "POST") then
if (os.getenv("HTTP_CONTENT_TYPE") ~= "application/x-www-form-urlencoded") then if (os.getenv("HTTP_CONTENT_TYPE") ~= "application/x-www-form-urlencoded") then
@ -60,45 +73,30 @@ function cgi.init()
else else
cgi.http_error(405, "Method not allowed", "I only do GET and POST.") cgi.http_error(405, "Method not allowed", "I only do GET and POST.")
end end
end
function cgi.read_hex()
local a = getc() or 0
local b = getc() or 0
return string.char(tonumber(a, 16)*16 + tonumber(b, 16))
end
function cgi.item()
local val = ""
cgi.fields = {}
while (true) do while (true) do
local c = getc() local k = item()
if ((c == nil) or (c == "=") or (c == "&")) then local v = item()
return val
elseif (c == "%") then
c = read_hex()
elseif (c == "+") then
c = " "
end
val = val .. c
end
end
function cgi.fields()
local ret = {}
while (true) do
local k = cgi.item()
local v = cgi.item()
if (k == "") then if (k == "") then
return ret break
end end
ret[k] = v cgi.fields[k] = v
end end
end end
function cgi.http_error(code, name, info)
print(code .. " " .. name)
print("Allow: GET POST")
print("Content-type: text/html")
print()
print("<h1>" .. code .. " " .. name .. "</h1>")
print("<p>" .. info .. "</p>")
os.exit(0)
end
function cgi.escape(s) function cgi.escape(s)
s = string.gsub(s, "&", "&amp;") s = string.gsub(s, "&", "&amp;")
s = string.gsub(s, "<", "&lt;") s = string.gsub(s, "<", "&lt;")
@ -106,4 +104,6 @@ function cgi.escape(s)
return s return s
end end
init()
return cgi return cgi

View File

@ -2,10 +2,13 @@
local cgi = require "cgi" local cgi = require "cgi"
cgi.init()
fields = cgi.fields() -- Read in team and answer
print("Content-type: text/html") print("Content-type: text/html")
print() print()
print("<pre>") print("<pre>")
print(fields["t"]) print(cgi.fields["t"])
print("</pre>") print("</pre>")