Merge LuCIttpd
[project/luci.git] / libs / sgi-luci / luasrc / ttpd / handler / luci.lua
1 --[[
2
3 HTTP server implementation for LuCI - luci handler
4 (c) 2008 Steven Barth <steven@midlink.org>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 $Id$
13
14 ]]--
15 local dsp = require "luci.dispatcher"
16 local util = require "luci.util"
17 local http = require "luci.http"
18 local ltn12 = require "luci.ltn12"
19 local mod = require "luci.ttpd.module"
20 local table = require "table"
21 local coroutine = require "coroutine"
22
23 module "luci.ttpd.handler.luci"
24
25 Luci = util.class(mod.Handler)
26 Response = mod.Response
27
28 function Luci.__init__(self, limit)
29 mod.Handler.__init__(self)
30 end
31
32 function Luci.handle_head(self, ...)
33 return (self:handle_get(...))
34 end
35
36 function Luci.handle_post(self, ...)
37 return self:handle_get(...)
38 end
39
40 function Luci.handle_get(self, request, sourcein, sinkerr)
41 local r = http.Request(
42 request.env,
43 sourcein,
44 sinkerr
45 )
46
47 local res, id, data1, data2 = true, 0, nil, nil
48 local headers = {}
49 local status = 200
50 local active = true
51
52 local x = coroutine.create(dsp.httpdispatch)
53 while not id or id < 3 do
54 res, id, data1, data2 = coroutine.resume(x, r)
55
56 if not res then
57 status = 500
58 headers["Content-Type"] = "text/plain"
59 local err = {id}
60 return Response( status, headers ), function() return table.remove(err) end
61 end
62
63 if id == 1 then
64 status = data1
65 elseif id == 2 then
66 headers[data1] = data2
67 end
68 end
69
70 local function iter()
71 local res, id, data = coroutine.resume(x)
72 if not res then
73 return nil, id
74 elseif not id or not active then
75 return true
76 elseif id == 5 then
77 active = false
78
79 while (coroutine.resume(x)) do
80 end
81
82 return nil
83 elseif id == 4 then
84 return data
85 end
86 if coroutine.status(x) == "dead" then
87 return nil
88 end
89 end
90
91 return Response(status, headers), iter
92 end