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+(.+)$");
22 if not method and key:sub(1,1) == "/" then
23 method, path = "GET", key;
27 path = normalize_path(path);
28 return method:upper().." "..host..app_path..path;
31 function module.add_host(module)
32 local host = module.host;
34 module.environment.apps = apps;
35 local function http_app_added(event)
36 local app_name = event.item.name;
37 local default_app_path = event.item.default_path or "/"..app_name;
38 local app_path = normalize_path(module:get_option_string(app_name.."_http_path", default_app_path));
41 module:log("error", "HTTP app has no 'name', add one or use module:provides('http', app)");
44 apps[app_name] = apps[app_name] or {};
45 local app_handlers = apps[app_name];
46 for key, handler in pairs(event.item.route or {}) do
47 local event_name = get_http_event(host, app_path, key);
49 if event_name:sub(-2, -1) == "/*" then
50 local base_path = event_name:match("/(.+)/*$");
51 local _handler = handler;
52 handler = function (event)
53 local path = event.request.path:sub(#base_path+1);
54 return _handler(event, path);
57 if not app_handlers[event_name] then
58 app_handlers[event_name] = handler;
59 server.add_handler(event_name, handler);
61 module:log("warn", "App %s added handler twice for '%s', ignoring", app_name, event_name);
64 module:log("error", "Invalid route in %s: %q", app_name, key);
69 local function http_app_removed(event)
70 local app_handlers = apps[event.item.name];
71 apps[event.item.name] = nil;
72 for event, handler in pairs(app_handlers) do
73 server.remove_handler(event, handler);
77 module:handle_items("http-provider", http_app_added, http_app_removed);
80 module:add_item("net-provider", {
82 listener = server.listener;
89 module:add_item("net-provider", {
91 listener = server.listener;