summaryrefslogtreecommitdiffhomepage
path: root/default.lua
blob: 56e50824dc07bef1dbbd1331e3c06b4df1145705 (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
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"

--- Default client request handler.
-- TODO: Add documentation once request and response API are more stable.
return function (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
	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: close\r\n",
		"Content-Length: ", #response, "\r\n",
		"Content-Type: text/html\r\n\r\n", response)
	stream:flush()
end