webmcp

view framework/env/request/handler.lua @ 291:fa3a5bba0067

Cache control; Added documentation for request.add_header(...)
author jbe
date Sun Mar 22 17:03:01 2015 +0100 (2015-03-22)
parents 81711c529eb2
children c1b561ee56c1
line source
1 --[[--
2 request.handler(
3 http_request, -- HTTP request object
4 close -- boolean indicating whether the server should announce to close the connection
5 )
7 Called by mcp.lua to process an HTTP request. Performs some initializations, calls request.router(), and handles the request.
9 --]]--
11 local function file_exists(filename)
12 local file = io.open(filename, "r")
13 if file then
14 io.close(file)
15 return true
16 else
17 return false
18 end
19 end
21 function request.handler(http_request, close)
22 _G.app = {} -- may be overwritten or modified by request initializers
23 do
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()
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 if #relative_baseurl_elements > 0 then
38 request._relative_baseurl = table.concat(relative_baseurl_elements)
39 else
40 request._relative_baseurl = "./"
41 end
42 else
43 request._relative_baseurl = nil
44 end
45 request._route = request.router() or {}
46 do
47 local post_id = http_request.post_params["_webmcp_id"]
48 if post_id then
49 request._route.id = post_id
50 end
51 end
53 if close then
54 request.add_header("Connection", "close")
55 end
57 local success, error_info = xpcall(
58 function()
60 if request._route.static then
61 local f, errmsg = io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r")
62 if not f then
63 if request.get_404_route() then
64 request.set_status("404 Not Found")
65 request.forward(request.get_404_route())
66 return
67 else
68 error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
69 end
70 end
71 local d = assert(f:read("*a"))
72 f:close()
73 slot.put_into("data", d)
74 local filename_extension = string.match(request._route.static, "%.([^.]+)$")
75 slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
76 return
77 end
79 -- restore slots if coming from http redirect
80 local tempstore_value = http_request.get_params["_tempstore"]
81 if tempstore_value then
82 trace.restore_slots{}
83 local blob = tempstore.pop(tempstore_value)
84 if blob then slot.restore_all(blob) end
85 end
87 if request.get_action() then
88 trace.request{
89 module = request.get_module(),
90 action = request.get_action()
91 }
92 if
93 request.get_404_route() and
94 not file_exists(
95 encode.action_file_path{
96 module = request.get_module(),
97 action = request.get_action()
98 }
99 )
100 then
101 request.set_status("404 Not Found")
102 request.forward(request.get_404_route())
103 else
104 if http_request.method ~= "POST" then
105 request.set_status("405 Method Not Allowed")
106 request.add_header("Allow", "POST")
107 error("Tried to invoke an action with a GET request.")
108 end
109 local action_status = execute.filtered_action{
110 module = request.get_module(),
111 action = request.get_action(),
112 }
113 if not request.is_rerouted() then
114 local routing_mode, routing_module, routing_view, routing_anchor
115 routing_mode = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
116 routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
117 routing_view = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
118 routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
119 if not (routing_mode or routing_module or routing_view) then
120 action_status = "default"
121 routing_mode = http_request.post_params["_webmcp_routing.default.mode"]
122 routing_module = http_request.post_params["_webmcp_routing.default.module"]
123 routing_view = http_request.post_params["_webmcp_routing.default.view"]
124 routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
125 end
126 assert(routing_module, "Routing information has no module.")
127 assert(routing_view, "Routing information has no view.")
128 if routing_mode == "redirect" then
129 local routing_params = {}
130 for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
131 local status, stripped_key = string.match(
132 key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
133 )
134 if status == action_status then
135 routing_params[stripped_key] = value
136 end
137 end
138 request.redirect{
139 module = routing_module,
140 view = routing_view,
141 id = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
142 params = routing_params,
143 anchor = routing_anchor
144 }
145 elseif routing_mode == "forward" then
146 request.forward{ module = routing_module, view = routing_view }
147 else
148 error("Missing or unknown routing mode in request parameters.")
149 end
150 end
151 end
152 else
153 -- no action
154 trace.request{
155 module = request.get_module(),
156 view = request.get_view()
157 }
158 if
159 request.get_404_route() and
160 not file_exists(
161 encode.view_file_path{
162 module = request.get_module(),
163 view = request.get_view()
164 }
165 )
166 then
167 request.set_status("404 Not Found")
168 request.forward(request.get_404_route())
169 end
170 end
172 if not request.get_redirect_data() then
173 request.process_forward()
174 local view = request.get_view()
175 if string.find(view, "^_") then
176 error("Tried to call a private view (prefixed with underscore).")
177 end
178 execute.filtered_view{
179 module = request.get_module(),
180 view = view,
181 }
182 end
184 end,
186 function(errobj)
187 return {
188 errobj = errobj,
189 stacktrace = string.gsub(
190 debug.traceback('', 2),
191 "^\r?\n?stack traceback:\r?\n?", ""
192 )
193 }
194 end
195 )
197 if not success then trace.error{} end
199 -- TODO: extend trace system to generally monitor execution time
200 -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
202 slot.select('trace', trace.render) -- render trace information
204 local redirect_data = request.get_redirect_data()
206 -- log error and switch to error layout, unless success
207 if not success then
208 local errobj = error_info.errobj
209 local stacktrace = error_info.stacktrace
210 if not request._status then
211 request._status = "500 Internal Server Error"
212 end
213 slot.set_layout('system_error')
214 slot.select('system_error', function()
215 if getmetatable(errobj) == mondelefant.errorobject_metatable then
216 slot.put(
217 "<p>Database error of class <b>",
218 encode.html(errobj.code),
219 "</b> occured:<br/><b>",
220 encode.html(errobj.message),
221 "</b></p>"
222 )
223 else
224 slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
225 end
226 slot.put("<p>Stack trace follows:<br/>")
227 slot.put(encode.html_newlines(encode.html(stacktrace)))
228 slot.put("</p>")
229 end)
230 elseif redirect_data then
231 redirect_data = table.new(redirect_data)
232 redirect_data.params = table.new(redirect_data.params)
233 local slot_dump = slot.dump_all()
234 if slot_dump ~= "" then
235 redirect_data.params.tempstore = tempstore.save(slot_dump)
236 end
237 http_request:send_status("303 See Other")
238 for i, header in ipairs(request._response_headers) do
239 http_request:send_header(header[1], header[2])
240 end
241 http_request:send_header("Location", encode.url(redirect_data))
242 http_request:finish()
243 end
245 if not success or not redirect_data then
247 http_request:send_status(request._status or "200 OK")
248 for i, header in ipairs(request._response_headers) do
249 http_request:send_header(header[1], header[2])
250 end
251 if not request._cache_manual then
252 local cache_time = request._cache_time
253 if request._cache and cache_time and cache_time > 0 then
254 http_request:send_header("Cache-Control", "max-age=" .. cache_time)
255 else
256 http_request:send_header("Cache-Control", "no-cache")
257 end
258 end
259 http_request:send_header("Content-Type", slot.get_content_type())
260 http_request:send_data(slot.render_layout())
261 http_request:finish()
262 end
264 end
266 --//--
268 --[[--
269 app -- table to store an application state
271 'app' is a global table for storing any application state data. It will be reset for every request.
272 --]]--
274 -- Initialized in request.handler(...).
276 --//--

Impressum / About Us