webmcp

view framework/env/request/handler.lua @ 255:9e4be058959d

New functions request.add_initializer(...) and request.add_variable(...) to allow per-request initialization; Merged request.process() with request.handler(...)
author jbe
date Sat Mar 14 23:39:47 2015 +0100 (2015-03-14)
parents 3db6f3ad0703
children 46f0083889a9
line source
1 --[[--
2 request.handler(
3 request -- HTTP request object
4 )
6 Called by mcp.lua to process an HTTP request. Performs some initializations, calls request.router(), and handles the request.
8 --]]--
10 local function file_exists(filename)
11 local file = io.open(filename, "r")
12 if file then
13 io.close(file)
14 return true
15 else
16 return false
17 end
18 end
20 -- TODO: function incomplete yet
21 function request.handler(http_request)
22 do
23 local first = not request._in_progress
24 request._in_progress = true -- NOTE: must be set to true before initializer functions are called
25 for i, func in ipairs(request._initializers) do
26 func(first)
27 end
28 end
30 request._http_request = http_request
31 local path = http_request.path
32 if path then
33 local relative_baseurl_elements = {}
34 for match in string.gmatch(path, "/") do
35 relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
36 end
37 request._relative_baseurl = table.concat(relative_baseurl_elements)
38 else
39 request._relative_baseurl = nil
40 end
41 request._route = request.router() or {}
43 local success, error_info = xpcall(
44 function()
46 if request._route.static then
47 local f = assert(io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r"))
48 local d = f:read("*a")
49 f:close()
50 slot.put_into("data", d)
51 slot.set_layout(nil, "application/octet-stream") -- TODO
52 return
53 end
55 -- restore slots if coming from http redirect
56 local tempstore_value = http_request.get_params["_tempstore"]
57 if tempstore_value then
58 trace.restore_slots{}
59 local blob = tempstore.pop(tempstore_value)
60 if blob then slot.restore_all(blob) end
61 end
63 if request.get_action() then
64 trace.request{
65 module = request.get_module(),
66 action = request.get_action()
67 }
68 if
69 request.get_404_route() and
70 not file_exists(
71 encode.action_file_path{
72 module = request.get_module(),
73 action = request.get_action()
74 }
75 )
76 then
77 request.set_status("404 Not Found")
78 request.forward(request.get_404_route())
79 else
80 if http_request.method ~= "POST" then
81 request.set_status("405 Method Not Allowed")
82 request.add_header("Allow", "POST")
83 error("Tried to invoke an action with a GET request.")
84 end
85 local action_status = execute.filtered_action{
86 module = request.get_module(),
87 action = request.get_action(),
88 }
89 if not request.is_rerouted() then
90 local routing_mode, routing_module, routing_view, routing_anchor
91 routing_mode = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
92 routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
93 routing_view = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
94 routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
95 if not (routing_mode or routing_module or routing_view) then
96 action_status = "default"
97 routing_mode = http_request.post_params["_webmcp_routing.default.mode"]
98 routing_module = http_request.post_params["_webmcp_routing.default.module"]
99 routing_view = http_request.post_params["_webmcp_routing.default.view"]
100 routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
101 end
102 assert(routing_module, "Routing information has no module.")
103 assert(routing_view, "Routing information has no view.")
104 if routing_mode == "redirect" then
105 local routing_params = {}
106 for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
107 local status, stripped_key = string.match(
108 key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
109 )
110 if status == action_status then
111 routing_params[stripped_key] = value
112 end
113 end
114 request.redirect{
115 module = routing_module,
116 view = routing_view,
117 id = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
118 params = routing_params,
119 anchor = routing_anchor
120 }
121 elseif routing_mode == "forward" then
122 request.forward{ module = routing_module, view = routing_view }
123 else
124 error("Missing or unknown routing mode in request parameters.")
125 end
126 end
127 end
128 else
129 -- no action
130 trace.request{
131 module = request.get_module(),
132 view = request.get_view()
133 }
134 if
135 request.get_404_route() and
136 not file_exists(
137 encode.view_file_path{
138 module = request.get_module(),
139 view = request.get_view()
140 }
141 )
142 then
143 request.set_status("404 Not Found")
144 request.forward(request.get_404_route())
145 end
146 end
148 if not request.get_redirect_data() then
149 request.process_forward()
150 local view = request.get_view()
151 if string.find(view, "^_") then
152 error("Tried to call a private view (prefixed with underscore).")
153 end
154 execute.filtered_view{
155 module = request.get_module(),
156 view = view,
157 }
158 end
160 -- force error due to missing absolute base URL until its too late to display error message
161 --if request.get_redirect_data() then
162 -- request.get_absolute_baseurl()
163 --end
165 end,
167 function(errobj)
168 return {
169 errobj = errobj,
170 stacktrace = string.gsub(
171 debug.traceback('', 2),
172 "^\r?\n?stack traceback:\r?\n?", ""
173 )
174 }
175 end
176 )
178 if not success then trace.error{} end
180 -- TODO: extend trace system to generally monitor execution time
181 -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
183 slot.select('trace', trace.render) -- render trace information
185 local redirect_data = request.get_redirect_data()
187 -- log error and switch to error layout, unless success
188 if not success then
189 local errobj = error_info.errobj
190 local stacktrace = error_info.stacktrace
191 if not request._status then
192 request._status = "500 Internal Server Error"
193 end
194 slot.set_layout('system_error')
195 slot.select('system_error', function()
196 if getmetatable(errobj) == mondelefant.errorobject_metatable then
197 slot.put(
198 "<p>Database error of class <b>",
199 encode.html(errobj.code),
200 "</b> occured:<br/><b>",
201 encode.html(errobj.message),
202 "</b></p>"
203 )
204 else
205 slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
206 end
207 slot.put("<p>Stack trace follows:<br/>")
208 slot.put(encode.html_newlines(encode.html(stacktrace)))
209 slot.put("</p>")
210 end)
211 elseif redirect_data then
212 local redirect_params = {}
213 for key, value in pairs(redirect_data.params) do
214 redirect_params[key] = value
215 end
216 local slot_dump = slot.dump_all()
217 if slot_dump ~= "" then
218 redirect_params.tempstore = tempstore.save(slot_dump)
219 end
220 http_request:send_status("303 See Other")
221 http_request:send_header("Connection", "close") -- TODO: extend moonbridge
222 http_request:send_header(
223 "Location",
224 encode.url{
225 base = request.get_absolute_baseurl(),
226 module = redirect_data.module,
227 view = redirect_data.view,
228 id = redirect_data.id,
229 params = redirect_params,
230 anchor = redirect_data.anchor
231 }
232 )
233 http_request:finish()
234 end
236 if not success or not redirect_data then
238 http_request:send_status(request._status or "200 OK")
239 http_request:send_header("Connection", "close") -- TODO: extend moonbridge
240 for i, header in ipairs(request._response_headers) do
241 http_request:send_header(header[1], header[2])
242 end
243 http_request:send_header("Content-Type", slot.get_content_type())
244 http_request:send_data(slot.render_layout())
245 http_request:finish()
246 end
248 end

Impressum / About Us