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+(.+)$");
21 if not method then -- No path specified, default to "" (base path)
22 method, path = key, "";
24 if method:sub(1,1) == "/" then
27 return method:upper().." "..host..app_path..path;
30 local function get_base_path(host_module, app_name, default_app_path)
31 return host_module:get_option("http_paths", {})[app_name] -- Host
32 or module:get_option("http_paths", {})[app_name] -- Global
33 or default_app_path; -- Default
36 function module.add_host(module)
37 local host = module.host;
39 module.environment.apps = apps;
40 local function http_app_added(event)
41 local app_name = event.item.name;
42 local default_app_path = event.item.default_path or "/"..app_name;
43 local app_path = normalize_path(get_base_path(module, app_name, default_app_path));
46 module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)");
49 apps[app_name] = apps[app_name] or {};
50 local app_handlers = apps[app_name];
51 for key, handler in pairs(event.item.route or {}) do
52 local event_name = get_http_event(host, app_path, key);
54 if event_name:sub(-2, -1) == "/*" then
55 local base_path = event_name:match("/(.+)/*$");
56 local _handler = handler;
57 handler = function (event)
58 local path = event.request.path:sub(#base_path+1);
59 return _handler(event, path);
62 if not app_handlers[event_name] then
63 app_handlers[event_name] = handler;
64 module:hook_object_event(server, event_name, handler);
66 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
69 module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key);
74 local function http_app_removed(event)
75 local app_handlers = apps[event.item.name];
76 apps[event.item.name] = nil;
77 for event, handler in pairs(app_handlers) do
78 module:unhook_object_event(server, event, handler);
82 module:handle_items("http-provider", http_app_added, http_app_removed);
85 module:add_item("net-provider", {
87 listener = server.listener;
94 module:add_item("net-provider", {
96 listener = server.listener;