2 -- Copyright (C) 2008-2012 Matthew Wild
3 -- Copyright (C) 2008-2012 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
11 local server = require "net.http.server";
13 local function normalize_path(path)
14 if path:sub(1,1) ~= "/" then path = "/"..path; end
15 if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end
19 local function get_http_event(host, app_path, key)
20 local method, path = key:match("^(%S+)%s+(.+)$");
22 if key:sub(1,1) ~= "/" then
25 method, path = "GET", key;
27 path = normalize_path(path);
28 return method:upper().." "..host..app_path..path;
31 local function get_base_path(host_module, app_name, default_app_path)
32 return host_module:get_option("http_paths", {})[app_name] -- Host
33 or module:get_option("http_paths", {})[app_name] -- Global
34 or default_app_path; -- Default
37 function module.add_host(module)
38 local host = module.host;
40 module.environment.apps = apps;
41 local function http_app_added(event)
42 local app_name = event.item.name;
43 local default_app_path = event.item.default_path or "/"..app_name;
44 local app_path = normalize_path(get_base_path(module, app_name, default_app_path));
47 module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)");
50 apps[app_name] = apps[app_name] or {};
51 local app_handlers = apps[app_name];
52 for key, handler in pairs(event.item.route or {}) do
53 local event_name = get_http_event(host, app_path, key);
55 if event_name:sub(-2, -1) == "/*" then
56 local base_path = event_name:match("/(.+)/*$");
57 local _handler = handler;
58 handler = function (event)
59 local path = event.request.path:sub(#base_path+1);
60 return _handler(event, path);
63 if not app_handlers[event_name] then
64 app_handlers[event_name] = handler;
65 module:hook_object_event(server, event_name, handler);
67 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
70 module:log("error", "Invalid route in %s: %q", app_name, key);
75 local function http_app_removed(event)
76 local app_handlers = apps[event.item.name];
77 apps[event.item.name] = nil;
78 for event, handler in pairs(app_handlers) do
79 module:unhook_object_event(server, event, handler);
83 module:handle_items("http-provider", http_app_added, http_app_removed);
86 module:add_item("net-provider", {
88 listener = server.listener;
95 module:add_item("net-provider", {
97 listener = server.listener;