Comparison

net/http/server.lua @ 4668:cce0c739b0d7

net.http.server: Support for wildcard events (events that end with '/*')
author Matthew Wild <mwild1@gmail.com>
date Mon, 23 Apr 2012 21:29:18 +0100
parent 4659:d53142e90cd0
child 4682:9d90c70b6358
comparison
equal deleted inserted replaced
4667:d0cfc49f3f2b 4668:cce0c739b0d7
19 19
20 local sessions = {}; 20 local sessions = {};
21 local handlers = {}; 21 local handlers = {};
22 22
23 local listener = {}; 23 local listener = {};
24
25 local function is_wildcard_event(event)
26 return event:sub(-2, -1) == "/*";
27 end
28 local function is_wildcard_match(wildcard_event, event)
29 log("debug", "comparing %q with %q", wildcard_event:sub(1, -2), event:sub(1, #wildcard_event-1));
30 return wildcard_event:sub(1, -2) == event:sub(1, #wildcard_event-1);
31 end
32
33 local event_map = events._event_map;
34 setmetatable(events._handlers, {
35 __index = function (handlers, curr_event)
36 if is_wildcard_event(curr_event) then return; end -- Wildcard events cannot be fired
37 -- Find all handlers that could match this event, sort them
38 -- and then put the array into handlers[event]
39 local matching_handlers_set = {};
40 local handlers_array = {};
41 for event, handlers_set in pairs(event_map) do
42 if event == curr_event or
43 is_wildcard_event(event) and is_wildcard_match(event, curr_event) then
44 for handler, priority in pairs(handlers_set) do
45 matching_handlers_set[handler] = { (select(2, event:gsub("/", "%1"))), priority };
46 table.insert(handlers_array, handler);
47 end
48 end
49 end
50 if #handlers_array == 0 then return; end
51 table.sort(handlers_array, function(b, a)
52 local a_score, b_score = matching_handlers_set[a], matching_handlers_set[b];
53 for i = 1, #a_score do
54 if a ~= b then -- If equal, compare next score value
55 return a_score[i] < b_score[i];
56 end
57 end
58 return false;
59 end);
60 handlers[curr_event] = handlers_array;
61 return handlers_array;
62 end;
63 __newindex = function (handlers, curr_event, handlers_array)
64 if handlers_array == nil
65 and is_wildcard_event(curr_event) then
66 -- Invalidate all matching
67 for event in pairs(handlers) do
68 if is_wildcard_match(curr_event, event) then
69 handlers[event] = nil;
70 end
71 end
72 end
73 end;
74 });
24 75
25 local handle_request; 76 local handle_request;
26 local _1, _2, _3; 77 local _1, _2, _3;
27 local function _handle_request() return handle_request(_1, _2, _3); end 78 local function _handle_request() return handle_request(_1, _2, _3); end
28 local function _traceback_handler(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end 79 local function _traceback_handler(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end