2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local httpserver = require "net.httpserver";
11 local t_concat, t_insert = table.concat, table.insert;
15 local response_404 = { status = "404 Not Found", body = "<h1>No such action</h1>Sorry, I don't have the action you requested" };
17 local control = require "core.actions".actions;
20 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = string.char(tonumber("0x"..k)); return t[k]; end });
22 local function urldecode(s)
23 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
26 local function query_to_table(query)
27 if type(query) == "string" and #query > 0 then
28 if query:match("=") then
30 for k, v in query:gmatch("&?([^=%?]+)=([^&%?]+)&?") do
32 params[urldecode(k)] = urldecode(v);
37 return urldecode(query);
44 local http_path = { http_base };
45 local function handle_request(method, body, request)
46 local path = request.url.path:gsub("^/[^/]+/", "");
50 for comp in path:gmatch("([^/]+)") do
57 if type(curr) == "table" then
59 for k,v in pairs(curr) do
60 t_insert(s, tostring(k));
62 if type(v) == "function" then
64 elseif type(v) == "table" then
67 t_insert(s, tostring(v));
72 elseif type(curr) == "function" then
73 local params = query_to_table(request.url.query);
74 params.host = request.headers.host:gsub(":%d+", "");
75 local ok, ret1, ret2 = pcall(curr, params);
77 return "EPIC FAIL: "..tostring(ret1);
79 return "FAIL: "..tostring(ret2);
81 return "OK: "..tostring(ret2);
86 httpserver.new{ port = 5280, base = "control", handler = handle_request, ssl = false }