Skip to content

Instantly share code, notes, and snippets.

@pingbird
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save pingbird/9984483 to your computer and use it in GitHub Desktop.

Select an option

Save pingbird/9984483 to your computer and use it in GitHub Desktop.
fail Lua HTTP server
local socket=require("socket")
local sv=socket.bind("*",80)
sv:settimeout(0)
local cli={}
local function tpairs(tbl)
local t={}
for k,v in pairs(tbl) do
table.insert(t,k)
end
local i=0
return function()
i=i+1
return t[i],tbl[t[i]]
end
end
local function formhttp(page)
return "HTTP/1.1 200 Found\r\nContent-Type: text/html\r\nContent-Length: "..#page.."\r\n\r\n"..page.."\r\n"
end
local function req(cl)
local cldat=cli[cl]
local o="<h1>"..(cldat.post or "Hello, World!").."</h1>"
o=o.."<form action=\"http://localhost/\" method=\"post\">"
o=o.."<p><input type=\"text\" name=\"text\"></p><input type=\"submit\" value=\"Submit\"></form><br>"
for k,v in pairs(cldat.header) do
o=o.."<br>["..k.."]="..v
end
cl:send(formhttp(o))
cl:close()
cli[cl]=nil
end
while true do
local cl=sv:accept()
while cl do
cl:settimeout(0)
cli[cl]={header={},ip=cl:getpeername()}
cl=sv:accept()
end
for cl,cldat in pairs(cli) do
local s,e=cl:receive(0)
if not s and e=="closed" then
cl:close()
cli[cl]=nil
else
local s,e=cl:receive(tonumber(cldat.post and cldat.header["Content-Length"]))
if s then
print(s)
if cldat.post then
cldat.post=s
req(cl)
elseif s=="" then
if cldat.method=="POST" then
cldat.post=""
elseif cldat.method=="GET" then
req(cl)
else
cl:close()
cli[cl]=nil
end
else
if not s:match(":") then
cldat.method=s:match("^(%S+)")
else
cldat.header[s:match("^(.-):")]=s:match("^.-: (.+)")
end
end
end
end
end
local sel={sv}
for k,v in pairs(cli) do
table.insert(sel,k)
end
socket.select(sel,nil,10)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment