Skip to content

Instantly share code, notes, and snippets.

@shiweifu
Created June 22, 2012 06:21
Show Gist options
  • Save shiweifu/2970761 to your computer and use it in GitHub Desktop.
Save shiweifu/2970761 to your computer and use it in GitHub Desktop.
lua static webserver
socket = require("socket")
httpcode = require("httpcode")
require("mime")
getMime = mime.getMime
assert(getMime)
function main( p )
local port
local server
if p ~= nil then
port = p
else
port = 80
end
server = assert(socket.bind("*", port))
server_poll(server)
end
function server_poll( server )
while 1 do
client = server:accept()
client:settimeout(60)
local request, err = client:receive()
if not err then
-- if request is kill (via telnet), stop the server
if request == "kill" then
client:send("Ladle has stopped\n")
print("Stopped")
break
else
-- begin serving content
serve(request)
end
end
end
end
-- serve requested content
function serve(request)
-- resolve requested file from client request
local file = string.match(request, "%w+%\/?.?%l+")
-- if no file mentioned in request, assume root file is index.html.
if file == nil then
file = "index.html"
end
-- retrieve mime type for file based on extension
local ext = string.match(file, "%\.%l%l%l%l?")
local mime,binary = getMime(ext)
-- reply with a response, which includes relevant mime type
if mime ~= nil then
client:send("HTTP/1.0 200/OK\r\nServer: tiny lua webserver\r\n")
client:send("Content-Type:" .. mime .. "\r\n\r\n")
end
-- load requested file in browser
local served, flags
if binary == false then
-- if file is ASCII, use just read flag
flags = "r"
else
-- otherwise file is binary, so also use binary flag (b)
-- note: this is for operating systems which read binary
-- files differently to plain text such as Windows
flags = "rb"
end
served = io.open("www/" .. file, flags)
if served ~= nil then
local content = served:read("*all")
client:send(content)
else
-- display not found error
err("Not found!")
end
-- done with client, close request
client:close()
end
-- display error message and server information
function err(message)
client:send(message)
end
main(9008)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment