webmcp
view framework/env/request/handler.lua @ 270:aedd13009ddc
Proper handling of 404's and mime types for static file delivery
| author | jbe | 
|---|---|
| date | Fri Mar 20 16:38:37 2015 +0100 (2015-03-20) | 
| parents | 56d237b81c18 | 
| children | ee7fcdade91d | 
 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     request._relative_baseurl = table.concat(relative_baseurl_elements)
    38   else
    39     request._relative_baseurl = nil
    40   end
    41   request._route = request.router() or {}
    43   if close then
    44     request.add_header("Connection", "close")
    45   end
    47   local success, error_info = xpcall(
    48     function()
    50       if request._route.static then
    51         local f, errmsg = io.open(WEBMCP_BASE_PATH .. "static/" .. request._route.static, "r")
    52         if not f then
    53           if request.get_404_route() then
    54             request.set_status("404 Not Found")
    55             request.forward(request.get_404_route())
    56             return
    57           else
    58             error('Could not open static file "' .. request._route.static .. '": ' .. errmsg)
    59           end
    60         end
    61         local d = assert(f:read("*a"))
    62         f:close()
    63         slot.put_into("data", d)
    64         local filename_extension = string.match(request._route.static, "%.([^.]+)$")
    65         slot.set_layout(nil, request._mime_types[filename_extension] or "application/octet-stream")
    66         return
    67       end
    69       -- restore slots if coming from http redirect
    70       local tempstore_value = http_request.get_params["_tempstore"]
    71       if tempstore_value then
    72         trace.restore_slots{}
    73         local blob = tempstore.pop(tempstore_value)
    74         if blob then slot.restore_all(blob) end
    75       end
    77       if request.get_action() then
    78         trace.request{
    79           module = request.get_module(),
    80           action = request.get_action()
    81         }
    82         if
    83           request.get_404_route() and
    84           not file_exists(
    85             encode.action_file_path{
    86               module = request.get_module(),
    87               action = request.get_action()
    88             }
    89           )
    90         then
    91           request.set_status("404 Not Found")
    92           request.forward(request.get_404_route())
    93         else
    94           if http_request.method ~= "POST" then
    95             request.set_status("405 Method Not Allowed")
    96             request.add_header("Allow", "POST")
    97             error("Tried to invoke an action with a GET request.")
    98           end
    99           local action_status = execute.filtered_action{
   100             module = request.get_module(),
   101             action = request.get_action(),
   102           }
   103           if not request.is_rerouted() then
   104             local routing_mode, routing_module, routing_view, routing_anchor
   105             routing_mode   = http_request.post_params["_webmcp_routing." .. action_status .. ".mode"]
   106             routing_module = http_request.post_params["_webmcp_routing." .. action_status .. ".module"]
   107             routing_view   = http_request.post_params["_webmcp_routing." .. action_status .. ".view"]
   108             routing_anchor = http_request.post_params["_webmcp_routing." .. action_status .. ".anchor"]
   109             if not (routing_mode or routing_module or routing_view) then
   110               action_status = "default"
   111               routing_mode   = http_request.post_params["_webmcp_routing.default.mode"]
   112               routing_module = http_request.post_params["_webmcp_routing.default.module"]
   113               routing_view   = http_request.post_params["_webmcp_routing.default.view"]
   114               routing_anchor = http_request.post_params["_webmcp_routing.default.anchor"]
   115             end
   116             assert(routing_module, "Routing information has no module.")
   117             assert(routing_view,   "Routing information has no view.")
   118             if routing_mode == "redirect" then
   119               local routing_params = {}
   120               for key, value in pairs(request.get_param_strings{ method="POST", include_internal=true }) do
   121                 local status, stripped_key = string.match(
   122                   key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
   123                 )
   124                 if status == action_status then
   125                   routing_params[stripped_key] = value
   126                 end
   127               end
   128               request.redirect{
   129                 module = routing_module,
   130                 view   = routing_view,
   131                 id     = http_request.post_params["_webmcp_routing." .. action_status .. ".id"],
   132                 params = routing_params,
   133                 anchor = routing_anchor
   134               }
   135             elseif routing_mode == "forward" then
   136               request.forward{ module = routing_module, view = routing_view }
   137             else
   138               error("Missing or unknown routing mode in request parameters.")
   139             end
   140           end
   141         end
   142       else
   143         -- no action
   144         trace.request{
   145           module = request.get_module(),
   146           view   = request.get_view()
   147         }
   148         if
   149           request.get_404_route() and
   150           not file_exists(
   151             encode.view_file_path{
   152               module = request.get_module(),
   153               view   = request.get_view()
   154             }
   155           )
   156         then
   157           request.set_status("404 Not Found")
   158           request.forward(request.get_404_route())
   159         end
   160       end
   162       if not request.get_redirect_data() then
   163         request.process_forward()
   164         local view = request.get_view()
   165         if string.find(view, "^_") then
   166           error("Tried to call a private view (prefixed with underscore).")
   167         end
   168         execute.filtered_view{
   169           module = request.get_module(),
   170           view   = view,
   171         }
   172       end
   174       -- force error due to missing absolute base URL until its too late to display error message
   175       --if request.get_redirect_data() then
   176       --  request.get_absolute_baseurl()
   177       --end
   179     end,
   181     function(errobj)
   182       return {
   183         errobj = errobj,
   184         stacktrace = string.gsub(
   185           debug.traceback('', 2),
   186           "^\r?\n?stack traceback:\r?\n?", ""
   187         )
   188       }
   189     end
   190   )
   192   if not success then trace.error{} end
   194   -- TODO: extend trace system to generally monitor execution time
   195   -- trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
   197   slot.select('trace', trace.render)  -- render trace information
   199   local redirect_data = request.get_redirect_data()
   201   -- log error and switch to error layout, unless success
   202   if not success then
   203     local errobj     = error_info.errobj
   204     local stacktrace = error_info.stacktrace
   205     if not request._status then
   206       request._status = "500 Internal Server Error"
   207     end
   208     slot.set_layout('system_error')
   209     slot.select('system_error', function()
   210       if getmetatable(errobj) == mondelefant.errorobject_metatable then
   211         slot.put(
   212           "<p>Database error of class <b>",
   213           encode.html(errobj.code),
   214           "</b> occured:<br/><b>",
   215           encode.html(errobj.message),
   216           "</b></p>"
   217         )
   218       else
   219         slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
   220       end
   221       slot.put("<p>Stack trace follows:<br/>")
   222       slot.put(encode.html_newlines(encode.html(stacktrace)))
   223       slot.put("</p>")
   224     end)
   225   elseif redirect_data then
   226     redirect_data = table.new(redirect_data)
   227     if redirect_data.base == nil then
   228       redirect_data.base = request.get_absolute_baseurl()
   229     end
   230     redirect_data.params = table.new(redirect_data.params)
   231     local slot_dump = slot.dump_all()
   232     if slot_dump ~= "" then
   233       redirect_data.params.tempstore = tempstore.save(slot_dump)
   234     end
   235     http_request:send_status("303 See Other")
   236     for i, header in ipairs(request._response_headers) do
   237       http_request:send_header(header[1], header[2])
   238     end
   239     http_request:send_header("Location", encode.url(redirect_data))
   240     http_request:finish()
   241   end
   243   if not success or not redirect_data then
   245     http_request:send_status(request._status or "200 OK")
   246     for i, header in ipairs(request._response_headers) do
   247       http_request:send_header(header[1], header[2])
   248     end
   249     http_request:send_header("Content-Type", slot.get_content_type())
   250     http_request:send_data(slot.render_layout())
   251     http_request:finish()
   252   end
   254 end
   256 --//--
   258 --[[--
   259 app  -- table to store an application state
   261 'app' is a global table for storing any application state data. It will be reset for every request.
   262 --]]--
   264 -- Initialized in request.handler(...).
   266 --//--
