xref: /netbsd-src/libexec/httpd/printenv.lua (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1-- $NetBSD: printenv.lua,v 1.3 2015/12/07 03:11:48 kamil Exp $
2
3-- this small Lua script demonstrates the use of Lua in (bozo)httpd
4-- it will simply output the "environment"
5
6-- Keep in mind that bozohttpd forks for each request when started in
7-- daemon mode, you can set global veriables here, but they will have
8-- the same value on each invocation.  You can not keep state between
9-- two calls.
10
11-- You can test this example by running the following command:
12-- /usr/libexec/httpd -b -f -I 8080 -L test printenv.lua .
13-- and then navigate to: http://127.0.0.1:8080/test/printenv
14
15local httpd = require 'httpd'
16
17function printenv(env, headers, query)
18
19	-- we get the "environment" in the env table, the values are more
20	-- or less the same as the variable for a CGI program
21
22	-- output headers using httpd.write()
23	-- httpd.write() will not append newlines
24	httpd.write("HTTP/1.1 200 Ok\r\n")
25	httpd.write("Content-Type: text/html\r\n\r\n")
26
27	-- output html using httpd.print()
28	-- you can also use print() and io.write() but they will not work with SSL
29	httpd.print([[
30		<html>
31			<head>
32				<title>Bozotic Lua Environment</title>
33			</head>
34			<body>
35				<h1>Bozotic Lua Environment</h1>
36	]])
37
38	httpd.print('module version: ' .. httpd._VERSION .. '<br>')
39
40	httpd.print('<h2>Server Environment</h2>')
41	-- print the list of "environment" variables
42	for k, v in pairs(env) do
43		httpd.print(k .. '=' .. v .. '<br/>')
44	end
45
46	httpd.print('<h2>Request Headers</h2>')
47	for k, v in pairs(headers) do
48		httpd.print(k .. '=' .. v .. '<br/>')
49	end
50
51	if query ~= nil then
52		httpd.print('<h2>Query Variables</h2>')
53		for k, v in pairs(query) do
54			httpd.print(k .. '=' .. v .. '<br/>')
55		end
56	end
57
58	httpd.print('<h2>Form Test</h2>')
59
60	httpd.print([[
61	<form method="POST" action="form?sender=me">
62	<input type="text" name="a_value">
63	<input type="submit">
64	</form>
65	]])
66	-- output a footer
67	httpd.print([[
68		</body>
69	</html>
70	]])
71end
72
73function form(env, header, query)
74
75	httpd.write("HTTP/1.1 200 Ok\r\n")
76	httpd.write("Content-Type: text/html\r\n\r\n")
77
78	if query ~= nil then
79		httpd.print('<h2>Form Variables</h2>')
80
81		if env.CONTENT_TYPE ~= nil then
82			httpd.print('Content-type: ' .. env.CONTENT_TYPE .. '<br>')
83		end
84
85		for k, v in pairs(query) do
86			httpd.print(k .. '=' .. v .. '<br/>')
87		end
88	else
89		httpd.print('No values')
90	end
91end
92
93-- register this handler for http://<hostname>/<prefix>/printenv
94httpd.register_handler('printenv', printenv)
95httpd.register_handler('form', form)
96