webmcp
view framework/env/request/handler.lua @ 353:f28b3c671378
Fixed indentation of autodoc comments
| author | jbe | 
|---|---|
| date | Thu Mar 26 16:55:13 2015 +0100 (2015-03-26) | 
| parents | 2b5bdf9028fb | 
| children | 545ec2e3eafa | 
 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 mcp.lua to process an HTTP request. Calls request.router(), and handles the request. Note: request initializers will have to be (automatically) executed before this function is invoked by mcp.lua.
     9 --]]--
    11 function request.handler(http_request)
    12   request._http_request = http_request
    13   local path = http_request.path
    14   if path then
    15     local relative_baseurl_elements = {}
    16     for match in string.gmatch(path, "/") do
    17       relative_baseurl_elements[#relative_baseurl_elements+1] = "../"
    18     end
    19     if #relative_baseurl_elements > 0 then
    20       request._relative_baseurl = table.concat(relative_baseurl_elements)
    21     else
    22       request._relative_baseurl = "./"
    23     end
    24   else
    25     request._relative_baseurl = nil
    26   end
    27   request._route = request.router()
    28   do
    29     local post_id = http_request.post_params["_webmcp_id"]
    30     if post_id then
    31       request._route.id = post_id
    32     end
    33   end
    35   local success, error_info = xpcall(
    36     function()
    38       if not request._route then
    39         request._route = {}
    40         if request.get_404_route() then
    41           request.set_status("404 Not Found")
    42           request.forward(request.get_404_route())
    43         else
    44           error("Could not route request URL")
    45         end
    46       end
    48       if request._route.static then
    49         local filename = WEBMCP_BASE_PATH .. "static/" .. request._route.static
    50         -- TODO: move sanitizer from request.default_router(...) to request.handler(...)
    51         local fstat, f, errmsg
    52         fstat, errmsg = extos.stat(filename)
    53         if fstat then
    54           if fstat.isdir then
    55             errmsg = "Is a directory"
    56           elseif not fstat.isreg then
    57             errmsg = "Not a regular file"
    58           else
    59             f, errmsg = io.open(filename, "r")
    60           end
    61         end
    62         if not f then
    63           request.set_status("404 Not Found")
    64           if request.get_404_route() then
    65             request.set_status("404 Not Found")
    66             request.forward(request.get_404_route())
    67           else
    68             error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
    69           end
    70         else
    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           request.allow_caching()
    77           return
    78         end
    79       end
    81       -- restore slots if coming from http redirect
    82       do
    83         local tempstore_value = http_request.get_params["_tempstore"]
    84         if tempstore_value then
    85           trace.restore_slots{}
    86           local blob = tempstore.pop(tempstore_value)
    87           if blob then slot.restore_all(blob) end
    88         end
    89       end
    91       if request.get_action() then
    92         trace.request{
    93           module = request.get_module(),
    94           action = request.get_action()
    95         }
    96         if
    97           request.get_404_route() and
    98           not execute.action{
    99             module = request.get_module(),
   100             action = request.get_action(),
   101             test_existence = true
   102           }
   103         then
   104           request.set_status("404 Not Found")
   105           request.forward(request.get_404_route())
   106         else
   107           if http_request.method ~= "POST" then
   108             request.set_status("405 Method Not Allowed")
   109             request.add_header("Allow", "POST")
   110             error("Tried to invoke an action with a GET request.")
   111           end
   112           local action_status = execute.filtered_action{
   113             module = request.get_module(),
   114             action = request.get_action(),
   115           }
   116           if not request.is_rerouted() then
   117             local routing_mode, routing_module, routing_view, routing_anchor
   118             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   119             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   120             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   121             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   122             if not (routing_mode or routing_module or routing_view) then
   123               action_status = "default"
   124               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   125               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   126               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   127               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   128             end
   129             assert(routing_module, "Routing information has no module.")
   130             assert(routing_view,   "Routing information has no view.")
   131             if routing_mode == "redirect" then
   132               local routing_params = {}
   133               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   134                 local status, stripped_key = string.match(
   135                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   136                 )
   137                 if status == action_status then
   138                   routing_params[stripped_key] = value
   139                 end
   140               end
   141               request.redirect{
   142                 module = routing_module,
   143                 view   = routing_view,
   144                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   145                 params = routing_params,
   146                 anchor = routing_anchor
   147               }
   148             elseif routing_mode == "forward" then
   149               request.forward{ module = routing_module, view = routing_view }
   150             else
   151               error("Missing or unknown routing mode in request parameters.")
   152             end
   153           end
   154         end
   155       else
   156         -- no action
   157         trace.request{
   158           module = request.get_module(),
   159           view   = request.get_view()
   160         }
   161         if
   162           request.get_404_route() and
   163           not execute.view{
   164             module = request.get_module(),
   165             view   = request.get_view(),
   166             test_existence = true
   167           }
   168         then
   169           request.set_status("404 Not Found")
   170           request.forward(request.get_404_route())
   171         end
   172       end
   174       if not request.get_redirect_data() then
   175         request.process_forward()
   176         local view = request.get_view()
   177         if string.find(view, "^_") then
   178           error("Tried to call a private view (prefixed with underscore).")
   179         end
   180         execute.filtered_view{
   181           module = request.get_module(),
   182           view   = view,
   183         }
   184       end
   186     end,
   188     function(errobj)
   189       return {
   190         errobj = errobj,
   191         stacktrace = string.gsub(
   192           debug.traceback('', 2),
   193           "^\r?\n?stack traceback:\r?\n?", ""
   194         )
   195       }
   196     end
   197   )
   199   if not success then trace.error{} end
   201   -- TODO: extend trace system to generally monitor execution time
   202   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   204   slot.select('trace', trace.render)  -- render trace information
   206   local redirect_data = request.get_redirect_data()
   208   -- log error and switch to error layout, unless success
   209   if not success then
   210     local errobj     = error_info.errobj
   211     local stacktrace = error_info.stacktrace
   212     if not request._status then
   213       request._status = "500 Internal Server Error"
   214     end
   215     http_request:close_after_finish()
   216     slot.set_layout('system_error')
   217     slot.select('system_error', function()
   218       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   219         slot.put(
   220           "<p>Database error of class <b>",
   221           encode.html(errobj.code),
   222           "</b> occured:<br/><b>",
   223           encode.html(errobj.message),
   224           "</b></p>"
   225         )
   226       else
   227         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   228       end
   229       slot.put("<p>Stack trace follows:<br/>")
   230       slot.put(encode.html_newlines(encode.html(stacktrace)))
   231       slot.put("</p>")
   232     end)
   233   elseif redirect_data then
   234     redirect_data = table.new(redirect_data)
   235     redirect_data.params = table.new(redirect_data.params)
   236     local slot_dump = slot.dump_all()
   237     if slot_dump ~= "" then
   238       redirect_data.params._tempstore = tempstore.save(slot_dump)
   239     end
   240     http_request:send_status("303 See Other")
   241     for i, header in ipairs(request._response_headers) do
   242       http_request:send_header(header[1], header[2])
   243     end
   244     http_request:send_header("Location", encode.url(redirect_data))
   245     http_request:finish()
   246   end
   248   if not success or not redirect_data then
   250     http_request:send_status(request._status or "200 OK")
   251     for i, header in ipairs(request._response_headers) do
   252       http_request:send_header(header[1], header[2])
   253     end
   254     if not request._cache_manual then
   255       local cache_time = request._cache_time
   256       if request._cache and cache_time and cache_time > 0 then
   257         http_request:send_header("Cache-Control", "max-age=" .. cache_time)
   258       else
   259         http_request:send_header("Cache-Control", "no-cache")
   260       end
   261     end
   262     http_request:send_header("Content-Type", slot.get_content_type())
   263     http_request:send_data(slot.render_layout())
   264     http_request:finish()
   265   end
   267   return success
   269 end
