Created
April 23, 2012 12:23
-
-
Save fogus/2470606 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- A web server in ~60 lines of Lua. Not counting utils. (Yes they are great utils.) | |
-- We're not faking this tho: The utils actually know nothing about HTTP. | |
-- We find out what port we should use. By default we use port 80 because we are REALLY hottish motherfuckers. | |
port = arg[1] or 80 | |
-- We import ourselves some great socket server maker tool. | |
require 'lib_genericsocketserver' | |
sources = {debug.getinfo(1).source:sub(2), 'lib_genericsocketserver.lua', 'lib_stefansutils.lua'} | |
-- And we make a socket server. | |
server = newGenericSocketServer(port) | |
server.overrides.newClientHandler = object(function(s) | |
firstLine = nil | |
function processLine(line) | |
--print('http: '..line) | |
if firstLine == nil then | |
firstLine = line | |
elseif trim(line) == '' then | |
-- end of request, send answer | |
local cmd, path = firstLine:match('^(%S+) *(%S+)') | |
print('cmd: '..tostring(cmd)..', path: '..tostring(path)) | |
local path2, query = path:match('^([^?]*)?(.*)$') | |
if query then path = path2 end | |
path = path:gsub('^/', '') | |
if cmd == 'GET' or cmd == 'POST' then | |
if path == '' then | |
local hits = readFile('hits') or 0 | |
hits = hits+1 | |
saveFile('hits', hits) | |
local html = [[ | |
<h1>Welcome to LuaForEverything!</h1><p>This is a pure Lua webserver comprising some 60 lines of Lua code. | |
No Apache is running. Current system time: $time.</p> | |
<p>Hit counter: $hits.</p> | |
<p>Server sources: $sources</p> | |
]] | |
html = html:gsub('$time', os.time()) | |
html = html:gsub('$sources', table.concat(map(sources, function(x) return '<a href="'..x..'">'..x..'</a>.' end), ' ')) | |
html = html:gsub('$hits', hits) | |
s:send('HTTP/1.0 200 OK\nContent-type: text/html\n\n'..html) | |
elseif isin(path, sources) then | |
s:send('HTTP/1.0 200 OK\nContent-type: text/plain\n\n'..(readFile(path) or 'oops')) | |
else | |
s:send('HTTP/1.0 440 Not found\n\n440 not found: '..path) | |
end | |
else | |
s:send('HTTP/1.0 500 Unknown command\n\nUnknown command') | |
end | |
server.closeSocket(s) | |
end | |
end | |
end) | |
server.go() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment