* Fixed last commit
[project/luci.git] / libs / httpd / luasrc / httpd / 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
16 module("luci.httpd.handler.luci", package.seeall)
17
18 require("luci.dispatcher")
19 require("luci.http")
20 require("luci.http.protocol.date")
21 require("ltn12")
22
23 Luci = luci.util.class(luci.httpd.module.Handler)
24 Response = luci.httpd.module.Response
25
26 function Luci.__init__(self)
27         luci.httpd.module.Handler.__init__(self)
28 end
29
30 function Luci.handle_head(self, ...)
31         local response, sourceout = self:handle_get(...)
32         return response
33 end
34
35 function Luci.handle_post(self, ...)
36         return self:handle_get(...)
37 end
38
39 function Luci.handle_get(self, request, sourcein, sinkerr)
40         local r = luci.http.Request(
41                 request.env,
42                 sourcein,
43                 sinkerr
44         )
45
46         local res, id, data1, data2 = true, 0, nil, nil
47         local headers = {}
48         local status = 200
49
50         local x = coroutine.create(luci.dispatcher.httpdispatch)
51         while not id or id < 3 do
52                 coroutine.yield()
53
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 then
75                         return true
76                 elseif id == 5 then
77                         return nil
78                 else
79                         return data
80                 end
81         end
82
83         headers["Expires"] = luci.http.protocol.date.to_http( os.time() )
84         headers["Date"]    = headers["Expires"]
85         headers["Cache-Control"] = "no-cache"
86
87         return Response(status, headers), iter
88 end