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 server.set_default_host(module:get_option_string("http_default_host"));
15 local function normalize_path(path)
16 if path:sub(1,1) ~= "/" then path = "/"..path; end
17 if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end
21 local function get_http_event(host, app_path, key)
22 local method, path = key:match("^(%S+)%s+(.+)$");
23 if not method then -- No path specified, default to "" (base path)
24 method, path = key, "";
26 if method:sub(1,1) == "/" then
29 return method:upper().." "..host..app_path..path;
32 local function get_base_path(host_module, app_name, default_app_path)
33 return host_module:get_option("http_paths", {})[app_name] -- Host
34 or module:get_option("http_paths", {})[app_name] -- Global
35 or default_app_path; -- Default
38 function module.add_host(module)
39 local host = module.host;
41 module.environment.apps = apps;
42 local function http_app_added(event)
43 local app_name = event.item.name;
44 local default_app_path = event.item.default_path or "/"..app_name;
45 local app_path = normalize_path(get_base_path(module, app_name, default_app_path));
48 module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)");
51 apps[app_name] = apps[app_name] or {};
52 local app_handlers = apps[app_name];
53 for key, handler in pairs(event.item.route or {}) do
54 local event_name = get_http_event(host, app_path, key);
56 if type(handler) ~= "function" then
58 handler = function () return data; end
59 elseif event_name:sub(-2, -1) == "/*" then
60 local base_path = event_name:match("/(.+)/*$");
61 local _handler = handler;
62 handler = function (event)
63 local path = event.request.path:sub(#base_path+1);
64 return _handler(event, path);
67 if not app_handlers[event_name] then
68 app_handlers[event_name] = handler;
69 module:hook_object_event(server, event_name, handler);
71 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
74 module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key);
79 local function http_app_removed(event)
80 local app_handlers = apps[event.item.name];
81 apps[event.item.name] = nil;
82 for event, handler in pairs(app_handlers) do
83 module:unhook_object_event(server, event, handler);
87 module:handle_items("http-provider", http_app_added, http_app_removed);
89 server.add_host(host);
90 function module.unload()
91 server.remove_host(host);
95 module:add_item("net-provider", {
97 listener = server.listener;
104 module:add_item("net-provider", {
106 listener = server.listener;