commit f73f29840ed09f1ec01cf3870ec228022080a142 Author: Paul Date: Sun Jun 2 17:02:36 2024 +0200 first commit diff --git a/hlib.lua b/hlib.lua new file mode 100644 index 0000000..24765bd --- /dev/null +++ b/hlib.lua @@ -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 diff --git a/http.data b/http.data new file mode 100644 index 0000000..b7d16f5 --- /dev/null +++ b/http.data @@ -0,0 +1,10 @@ +HTTP/1.1 200 OK +Server: webserver-lua-c +Content-type: text/html + + +http test + +

hello, world

+ + diff --git a/http.lua b/http.lua new file mode 100755 index 0000000..be71a26 --- /dev/null +++ b/http.lua @@ -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