1-- SAPI for CivetWeb
2-- Wrapper for the native "mg" interface
3
4SAPI = {}
5SAPI.Request = {}
6SAPI.Request.getpostdata = function(n)
7  local s = ""
8  s = mg.read(n)
9  return s
10end
11SAPI.Request.servervariable = function(varname)
12  local s
13  if varname == "REQUEST_METHOD" then
14     s = mg.request_info.request_method
15  elseif varname == "QUERY_STRING" then
16     s = mg.request_info.query_string
17  elseif varname == "SERVER_PORT" then
18     s = mg.request_info.server_port
19  elseif varname == "SERVER_NAME" then
20     s = mg.auth_domain
21  elseif varname == "PATH_INFO" then
22     s = mg.request_info.path_info
23  elseif varname == "AUTH_TYPE" then
24     s = mg.request_info.query_string
25  elseif varname == "REMOTE_ADDR" then
26     s = mg.request_info.remote_addr
27  elseif varname == "SERVER_SOFTWARE" then
28     s = "CivetWeb/" .. mg.version
29  elseif varname == "SERVER_PROTOCOL" then
30     s = "HTTP/1.1"
31  else
32     print(varname)
33  end
34  return s or ""
35end
36
37SAPI._CurrentResponse = {contenttype = "text/plain", header={}, written=false, status=200}
38
39SAPI.Response = {}
40SAPI.Response.contenttype = function(header)
41  SAPI._CurrentResponse.contenttype = header
42  print("Content: " .. header)
43end
44SAPI.Response.errorlog = function(message)
45  print("Error: " .. tostring(message))
46end
47SAPI.Response.header = function(header, value)
48  local t = SAPI._CurrentResponse.header
49  t[#t] = string.format("%s: %s", header, value)
50end
51SAPI.Response.redirect = function(uri)
52  print("Redirect: " .. uri)
53end
54SAPI.Response.write = function(...)
55  if not SAPI._CurrentResponse.written then
56    if arg[1]:sub(4) ~= "HTTP" then
57      mg.write("HTTP/1.1 " .. SAPI._CurrentResponse.status .. " " .. mg.get_response_code_text(SAPI._CurrentResponse.status) .. "\r\n")
58      mg.write("Content-Type: " .. SAPI._CurrentResponse.contenttype .. "\r\n")
59      for _,v in ipairs(SAPI._CurrentResponse.header) do
60        mg.write(v .. "\r\n")
61      end
62      mg.write("\r\n")
63    end
64    SAPI._CurrentResponse.written = true;
65  end
66  for _,v in ipairs(arg) do
67    mg.write(v)
68  end
69end
70
71
72-- Debug helper function to print a table
73function po(t)
74  print("Type: " .. type(t) .. ", Value: " .. tostring(t))
75  if type(t)=="table" then
76    for k,v in pairs(t) do
77      print(k,v)
78    end
79  end
80end
81
82-----------------------------------------------------
83
84
85-- Use cgilua interface
86-- require "cgilua"
87
88
89