summaryrefslogtreecommitdiffhomepage
path: root/default.lua
blob: bc409ef9b58c01e358ada4bdc99c597179f5e49e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
local RESPONSE = [[<!doctype html>
<html lang="en">
<title>plop</title>
<h1>Hello, from plop/lua!</h1>
<table>
<tr><th>Method<th>Path<th>Version
<tr><td>%s<td>%s<td>%s
</table>
<hr>
<table>
<tr><th>Header<th>Value
%s</table>
]]
local HEADER = "%s<tr><td>%s<td>%s\n"

local
function handle_request (stream)
	local status = 200
	local method, path, version, h = stream:read(" ", " ", "\r\n", "\r\n\r\n")
	local headers = {}
	if h then
		for header, value in h:gmatch "([^%s:]+)%s*:%s+([^\r\n]*)" do
			headers[header:lower()] = value
		end
	end
	local connection = headers.connection or "close"
	if method == nil or path == nil or version ~= "HTTP/1.1" or h == nil then
		status = 400
	end
	local headers_table = ""
	for header, value in pairs(headers) do
		headers_table = HEADER:format(headers_table, header, value)
	end
	local response = RESPONSE:format(method, path, version, headers_table)
	stream:write(
		"HTTP/1.1 ", status, "\r\n",
		"Connection: ", connection, "\r\n",
		"Content-Length: ", #response, "\r\n",
		"Content-Type: text/html\r\n\r\n", response)
	stream:flush()
	return connection
end

--- Default client request handler.
-- TODO: Add documentation once request and response API are more stable.
return
function (stream)
	repeat
		local connection = handle_request(stream)
	until connection == "close"
end