summaryrefslogtreecommitdiffhomepage
path: root/default.lua
blob: 71009273627c0acb224c8a144a14261fe7dccf2d (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
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)
	local headers = {Connection="close", ["Content-Length"]=#response, ["Content-Type"]="text/html"}
	return {status=status, headers=headers, data=response}
end