773d3c873dfd821dae28655a246eba7d8d83c5c1
[project/luci.git] / libs / httpd / luasrc / httpd.lua
1 --[[
2 LuCI - HTTPD
3 ]]--
4 module("luci.httpd", package.seeall)
5 require("luci.copas")
6 require("luci.http.protocol")
7 require("luci.sys")
8
9
10
11 function run(config)
12         -- TODO: process config
13         local server = socket.bind("0.0.0.0", 8080)
14         copas.addserver(server, spawnworker)
15         
16         while true do
17                 copas.step()
18         end
19 end
20
21
22 function spawnworker(socket)
23         socket = copas.wrap(socket)
24         local request = luci.http.protocol.parse_message_header(socket)
25         request.input = socket -- TODO: replace with streamreader
26         request.error = io.stderr
27         
28         
29         local output = socket -- TODO: replace with streamwriter
30         
31         -- TODO: detect matching handler
32         local h = luci.httpd.FileHandler.SimpleHandler(luci.sys.libpath() .. "/httpd/httest")
33         h:process(request, output)
34 end
35
36
37 Response = luci.util.class()
38 function Response.__init__(self, sourceout, headers, status)
39         self.sourceout = sourceout or function() end
40         self.headers   = headers or {}
41         self.status    = status or 200
42 end
43
44 function Response.addheader(self, key, value)
45         self.headers[key] = value
46 end
47
48 function Response.setstatus(self, status)
49         self.status = status
50 end
51
52 function Response.setsource(self, source)
53         self.sourceout = source
54 end
55
56
57 Handler = luci.util.class()
58 function Handler.__init__(self)
59         self.filter = {}
60 end
61
62 function Handler.addfilter(self, filter)
63         table.insert(self.filter, filter)
64 end
65
66 function Handler.process(self, request, output)
67         -- TODO: Process input filters
68
69         local response = self:handle(request)
70         
71         -- TODO: Process output filters
72         
73         output:send("HTTP/1.0 " .. response.status .. " BLA\r\n")
74         for k, v in pairs(response.headers) do
75                 output:send(k .. ": " .. v .. "\r\n")
76         end
77         
78         output:send("\r\n")
79
80         for chunk in response.sourceout do
81                 output:send(chunk)
82         end
83 end
84