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.
10 module:depends("http_errors");
12 local server = require "net.http.server";
14 server.set_default_host(module:get_option_string("http_default_host"));
16 local function normalize_path(path)
17 if path:sub(1,1) ~= "/" then path = "/"..path; end
18 if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end
22 local function get_http_event(host, app_path, key)
23 local method, path = key:match("^(%S+)%s+(.+)$");
24 if not method then -- No path specified, default to "" (base path)
25 method, path = key, "";
27 if method:sub(1,1) == "/" then
30 return method:upper().." "..host..app_path..path;
33 local function get_base_path(host_module, app_name, default_app_path)
34 return host_module:get_option("http_paths", {})[app_name] -- Host
35 or module:get_option("http_paths", {})[app_name] -- Global
36 or default_app_path; -- Default
39 function module.add_host(module)
40 local host = module.host;
42 module.environment.apps = apps;
43 local function http_app_added(event)
44 local app_name = event.item.name;
45 local default_app_path = event.item.default_path or "/"..app_name;
46 local app_path = normalize_path(get_base_path(module, app_name, default_app_path));
49 module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)");
52 apps[app_name] = apps[app_name] or {};
53 local app_handlers = apps[app_name];
54 for key, handler in pairs(event.item.route or {}) do
55 local event_name = get_http_event(host, app_path, key);
57 if type(handler) ~= "function" then
59 handler = function () return data; end
60 elseif event_name:sub(-2, -1) == "/*" then
61 local base_path = event_name:match("/(.+)/*$");
62 local _handler = handler;
63 handler = function (event)
64 local path = event.request.path:sub(#base_path+1);
65 return _handler(event, path);
68 if not app_handlers[event_name] then
69 app_handlers[event_name] = handler;
70 module:hook_object_event(server, event_name, handler);
72 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
75 module:log("error", "Invalid route in %s, %q. See http://prosody.im/doc/developers/http#routes", app_name, key);
80 local function http_app_removed(event)
81 local app_handlers = apps[event.item.name];
82 apps[event.item.name] = nil;
83 for event, handler in pairs(app_handlers) do
84 module:unhook_object_event(server, event, handler);
88 module:handle_items("http-provider", http_app_added, http_app_removed);
90 server.add_host(host);
91 function module.unload()
92 server.remove_host(host);
96 module:add_item("net-provider", {
98 listener = server.listener;
105 module:add_item("net-provider", {
107 listener = server.listener;