Created
June 24, 2024 19:23
-
-
Save Frityet/9fc8c7d12a38aa603b5f697b894679f3 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
local socket = require("socket") | |
local xml_gen = require("x-gen") | |
local xml = xml_gen.xml | |
---@param document XML.Node | |
local function build_response(document) | |
local str = "<!DOCTYPE html>"..tostring(document) | |
return ([[ | |
HTTP/1.1 200 OK | |
Content-Type: text/html | |
Content-Length: %d | |
%s | |
]]):format(#str, str) | |
end | |
local server = assert(socket.bind("*", 8080)) | |
local ip, port = server:getsockname() | |
print("Listening on port " .. port) | |
---@type thread[] | |
local clients = {} | |
---@param client TCPSocket | |
local function client_thread(client) | |
while true do | |
local req, err = client:receive() | |
if not err then | |
print(req) | |
local res = build_response ( | |
xml.html { | |
xml.head { | |
xml.title "Hello, World!" | |
}, | |
xml.body { | |
xml.h1 "Hello, World!", | |
xml.p "This is a simple HTTP server written in Lua.", | |
xml.p "The current time is "..os.date() | |
} | |
} | |
) | |
print(res) | |
assert(client:send(res)) | |
elseif err == "closed" then | |
client:close() | |
break | |
else | |
error(err) | |
end | |
coroutine.yield() | |
end | |
end | |
local function main() | |
while true do | |
---@type TCPSocket? | |
local client = server:accept() | |
if client then | |
client:settimeout(0) | |
table.insert(clients, coroutine.create(client_thread)) | |
coroutine.resume(clients[#clients], client) | |
end | |
coroutine.yield() | |
end | |
end | |
local main_thread = coroutine.create(main) | |
while true do | |
coroutine.resume(main_thread) | |
for i = #clients, 1, -1 do | |
if coroutine.status(clients[i]) == "dead" then | |
table.remove(clients, i) | |
else | |
coroutine.resume(clients[i]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very cool fritsta. i didn’t know i could embed this script!!