webmcp

view framework/env/request/handler.lua @ 497:d89813dd4d92

New function request.add_error_handler(...); Allow layout_ident to be passed directly to slot.render_layout(...)
author jbe
date Sun Jul 23 02:51:13 2017 +0200 (15 months ago)
parents 3b4dbabca31f
children
line source
1 --[[--
2 success = -- false if an error occurred, true otherwise
3 request.handler(
4 http_request -- HTTP request object
5 )
7 Called by bin/mcp.lua to process an HTTP request. Calls request.router() and handles the request. Note: request initializers (see request.initialize()) are to be executed by mcp.lua before this function is invoked by mcp.lua.
9 --]]--
11 function request.handler(http_request)
13 request._http_request = http_request
14 local path = http_request.path
15 if path then
16 local relative_baseurl_elements = {}
17 for match in string.gmatch(path, "/") do
18 relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
19 end
20 if #relative_baseurl_elements > 0 then
21 request._relative_baseurl = table.concat(relative_baseurl_elements)
22 else
23 request._relative_baseurl = "./"
24 end
25 else
26 request._relative_baseurl = nil
27 end
29 local success, error_info = xpcall(
30 function()
32 local function require_method(errmsg, ...)
33 for i = 1, select("#", ...) do
34 if http_request.method == select(i, ...) then return end
35 end
36 request.set_status("405 Method Not Allowed")
37 request.add_header("Allow", table.concat({...}, ", "))
38 error(errmsg)
39 end
41 request._route = request.router()
42 do
43 local post_id = http_request.post_params["_webmcp_id"]
44 if post_id then
45 request._route.id = post_id
46 end
47 end
48 local options_handler = loadcached(encode.file_path(
49 WEBMCP_BASE_PATH, 'app', WEBMCP_APP_NAME, 'http_options.lua'
50 ))
51 if options_handler then
52 options_handler()
53 end
54 if http_request.method == "OPTIONS" then
55 return
56 end
58 if not request._route then
59 request._route = {}
60 if request.get_404_route() then
61 request.set_status("404 Not Found")
62 request.forward(request.get_404_route())
63 else
64 error("Could not route request URL")
65 end
66 end
68 if request._route.static then
69 local subpath = request._route.static
70 local errmsg
71 for element in string.gmatch(subpath, "[^/]+") do
72 if element == "." or element == ".." then
73 errmsg = "Illegal path"
74 break
75 end
76 end
77 local fstat, f
78 if not errmsg then
79 local filename = WEBMCP_BASE_PATH .. "static/" .. subpath
80 fstat, errmsg = extos.stat(filename)
81 if fstat then
82 if fstat.isdir then
83 errmsg = "Is a directory"
84 elseif not fstat.isreg then
85 errmsg = "Not a regular file"
86 else
87 f, errmsg = io.open(filename, "r")
88 end
89 end
90 end
91 if not f then
92 if request.get_404_route() then
93 request.set_status("404 Not Found")
94 request.forward(request.get_404_route())
95 else
96 error('Could not open static file "' .. subpath .. '": ' .. errmsg)
97 end
98 else
99 require_method(
100 "Invalid HTTP method for static file",
101 "HEAD", "GET", "POST"
102 )
103 local d = assert(f:read("*a"))
104 f:close()
105 slot.put_into("data", d)
106 local filename_extension = string.match(subpath, "%.([^.]+)$")
107 slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
108 request.allow_caching()
109 return
110 end
111 end
113 -- restore slots if coming from http redirect
114 do
115 local tempstore_value = http_request.get_params["_tempstore"]
116 if tempstore_value then
117 trace.restore_slots{}
118 local blob = tempstore.pop(tempstore_value)
119 if blob then slot.restore_all(blob) end
120 end
121 end
123 if request.get_action() then
124 trace.request{
125 module = request.get_module(),
126 action = request.get_action()
127 }
128 if
129 not execute.action{
130 module = request.get_module(),
131 action = request.get_action(),
132 test_existence = true
133 } and
134 request.get_404_route()
135 then
136 request.set_status("404 Not Found")
137 request.forward(request.get_404_route())
138 else
139 require_method(
140 "Invalid HTTP method for action (POST request required)",
141 "POST"
142 )
143 local action_status = execute.filtered_action{
144 module = request.get_module(),
145 action = request.get_action(),
146 }
147 if not (request.is_rerouted() or slot.layout_is_set()) then
148 local routing_mode, routing_module, routing_view, routing_anchor
149 routing_mode = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
150 routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
151 routing_view = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
152 routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
153 if not (routing_mode or routing_module or routing_view) then
154 action_status = "default"
155 routing_mode = http_request.post_params["_webmcp_routing.default.mode"]
156 routing_module = http_request.post_params["_webmcp_routing.default.module"]
157 routing_view = http_request.post_params["_webmcp_routing.default.view"]
158 routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
159 end
160 assert(routing_module, "Routing information has no module.")
161 assert(routing_view, "Routing information has no view.")
162 if routing_mode == "redirect" then
163 local routing_params = {}
164 for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
165 local status, stripped_key = string.match(
166 key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
167 )
168 if status == action_status then
169 routing_params[stripped_key] = value
170 end
171 end
172 request.redirect{
173 module = routing_module,
174 view = routing_view,
175 id = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
176 params = routing_params,
177 anchor = routing_anchor
178 }
179 elseif routing_mode == "forward" then
180 request.forward{ module = routing_module, view = routing_view }
181 else
182 error("Missing or unknown routing mode in request parameters.")
183 end
184 end
185 end
186 else
187 -- no action
188 trace.request{
189 module = request.get_module(),
190 view = request.get_view()
191 }
192 if
193 not execute.view{
194 module = request.get_module(),
195 view = request.get_view(),
196 test_existence = true
197 } and request.get_404_route()
198 then
199 request.set_status("404 Not Found")
200 request.forward(request.get_404_route())
201 end
202 end
204 if not (request.get_redirect_data() or slot.layout_is_set()) then
205 request.process_forward()
206 local view = request.get_view()
207 if string.find(view, "^_") then
208 error("Tried to call a private view (prefixed with underscore).")
209 end
210 require_method(
211 "Invalid HTTP method",
212 "HEAD", "GET", "POST"
213 )
214 execute.filtered_view{
215 module = request.get_module(),
216 view = view,
217 }
218 end
220 end,
222 function(errobj)
223 return {
224 errobj = errobj,
225 stacktrace = string.gsub(
226 debug.traceback('', 2),
227 "^\r?\n?stack traceback:\r?\n?", ""
228 )
229 }
230 end
231 )
233 if not success then trace.error{} end
235 slot.select('trace', trace.render) -- render trace information
237 local redirect_data = request.get_redirect_data()
239 -- log error and switch to error layout, unless success
240 if not success then
241 local errobj = error_info.errobj
242 local stacktrace = error_info.stacktrace
243 if not request._status then
244 request._status = "500 Internal Server Error"
245 end
246 http_request:close_after_finish()
247 slot.set_layout('system_error')
248 slot.select('system_error', function()
249 if getmetatable(errobj) == mondelefant.errorobject_metatable then
250 slot.put(
251 "<p>Database error of class <b>",
252 encode.html(errobj.code),
253 "</b> occured:<br/><b>",
254 encode.html(errobj.message),
255 "</b></p>"
256 )
257 else
258 slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
259 end
260 slot.put("<p>Stack trace follows:<br/>")
261 slot.put(encode.html_newlines(encode.html(stacktrace)))
262 slot.put("</p>")
263 end)
264 for i, error_handler in ipairs(request._error_handlers) do
265 error_handler(error_info.errobj, error_info.stacktrace)
266 end
267 elseif redirect_data then
268 if
269 redirect_data.include_tempstore == true or (
270 redirect_data.include_tempstore ~= false and
271 not redirect_data.external
272 )
273 then
274 redirect_data = table.new(redirect_data)
275 redirect_data.params = table.new(redirect_data.params)
276 local slot_dump = slot.dump_all()
277 if slot_dump ~= "" then
278 redirect_data.params._tempstore = tempstore.save(slot_dump)
279 end
280 end
281 http_request:send_status("303 See Other")
282 for i, header in ipairs(request._response_headers) do
283 http_request:send_header(header[1], header[2])
284 end
285 http_request:send_header("Location", encode.url(redirect_data))
286 http_request:finish()
287 end
289 if not success or not redirect_data then
291 http_request:send_status(request._status or "200 OK")
292 for i, header in ipairs(request._response_headers) do
293 http_request:send_header(header[1], header[2])
294 end
295 if not request._cache_manual then
296 local cache_time = request._cache_time
297 if request._cache and cache_time and cache_time > 0 then
298 http_request:send_header("Cache-Control", "max-age=" .. cache_time)
299 else
300 http_request:send_header("Cache-Control", "no-cache")
301 end
302 end
303 http_request:send_header("Content-Type", slot.get_content_type())
304 http_request:send_data(slot.render_layout())
305 http_request:finish()
306 end
308 return success
310 end

Impressum / About Us