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 parse_url = require "socket.url".parse;
12 local server = require "net.http.server";
14 local function normalize_path(path)
15 if path:sub(1,1) ~= "/" then path = "/"..path; end
16 if path:sub(-1,-1) == "/" then path = path:sub(1, -2); end
20 local function get_http_event(host, app_path, key)
21 local method, path = key:match("^(%S+)%s+(.+)$");
23 if key:sub(1,1) ~= "/" then
26 method, path = "GET", key;
28 path = normalize_path(path);
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 event_name:sub(-2, -1) == "/*" then
57 local base_path = event_name:match("/(.+)/*$");
58 local _handler = handler;
59 handler = function (event)
60 local path = event.request.path:sub(#base_path+1);
61 return _handler(event, path);
64 if not app_handlers[event_name] then
65 app_handlers[event_name] = handler;
66 module:hook_object_event(server, event_name, handler);
68 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
71 module:log("error", "Invalid route in %s: %q", app_name, key);
76 local function http_app_removed(event)
77 local app_handlers = apps[event.item.name];
78 apps[event.item.name] = nil;
79 for event, handler in pairs(app_handlers) do
80 module:unhook_object_event(server, event, handler);
84 module:handle_items("http-provider", http_app_added, http_app_removed);
87 module:add_item("net-provider", {
89 listener = server.listener;
96 module:add_item("net-provider", {
98 listener = server.listener;