first commit

This commit is contained in:
Paul 2024-06-02 17:02:36 +02:00
commit f73f29840e
3 changed files with 77 additions and 0 deletions

37
hlib.lua Normal file
View File

@ -0,0 +1,37 @@
local hlib = {}
function hlib.parse_request(r)
local request = {method=nil, path=nil, version=nil, headers={}}
local lines = string.gmatch(r, "[^\n]+")
local head_msg = lines()
local _, _, method, path, version = string.find(head_msg, "(%u+) ([%w/]+) ([%w/%.]+)")
request.method = method
request.path = path
request.version = version
for line in lines do
local _, _, a, b = string.find(line, "([%w-]+): (.+)")
if a then
request.headers[a] = b
end
end
return request
end
function hlib.response(path, status, body)
local resp = {
version=fmt("HTTP/%s",g_version),
status=status,
status_msg=g_status_msg[status],
body=body,
headers={}
}
local r = fmt(
[[%s %s %s
%s
]], resp.version, resp.status, resp.status_msg, resp.body)
return r
end
return hlib

10
http.data Normal file
View File

@ -0,0 +1,10 @@
HTTP/1.1 200 OK
Server: webserver-lua-c
Content-type: text/html
<html>
<title>http test</title>
<body>
<p>hello, <span style="color:red;">world</span></p>
</body>
</html>

30
http.lua Executable file
View File

@ -0,0 +1,30 @@
#!/usr/bin/env lua5.4
local unix = require('unix')
local hlib = require('hlib')
local fmt = string.format
local g_version = "1.1"
local g_status_msg = {[200]="OK"}
local sock = unix.socket(unix.AF_INET, unix.SOCK_STREAM, 0)
unix.setsockopt(sock, unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
local listenaddr = unix.getaddrinfo("0.0.0.0","8080")()
local b = unix.bind(sock, listenaddr)
if not b then print("error binding socket") return end
unix.listen(sock, 1024)
while true do
unix.sleep(0.05)
local csock = unix.accept(sock, 0)
local msg = unix.recv(csock, 1024)
if msg then
local req = hlib.parse_request(msg)
local data = hlib.response(req.path, 200, "test")
unix.send(csock, data)
end
unix.shutdown(csock, 0)
unix.close(csock)
end