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 function module.add_host(module)
33 local host = module.host;
35 module.environment.apps = apps;
36 local function http_app_added(event)
37 local app_name = event.item.name;
38 local default_app_path = event.item.default_path or "/"..app_name;
39 local app_path = normalize_path(module:get_option_string(app_name.."_http_path", default_app_path));
42 module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)");
45 apps[app_name] = apps[app_name] or {};
46 local app_handlers = apps[app_name];
47 for key, handler in pairs(event.item.route or {}) do
48 local event_name = get_http_event(host, app_path, key);
50 if event_name:sub(-2, -1) == "/*" then
51 local base_path = event_name:match("/(.+)/*$");
52 local _handler = handler;
53 handler = function (event)
54 local path = event.request.path:sub(#base_path+1);
55 return _handler(event, path);
58 if not app_handlers[event_name] then
59 app_handlers[event_name] = handler;
60 server.add_handler(event_name, handler);
62 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
65 module:log("error", "Invalid route in %s: %q", app_name, key);
70 local function http_app_removed(event)
71 local app_handlers = apps[event.item.name];
72 apps[event.item.name] = nil;
73 for event, handler in pairs(app_handlers) do
74 server.remove_handler(event, handler);
78 module:handle_items("http-provider", http_app_added, http_app_removed);
81 module:add_item("net-provider", {
83 listener = server.listener;
90 module:add_item("net-provider", {
92 listener = server.listener;