2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
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
10 http://www.apache.org/licenses/LICENSE-2.0
15 local pcall, ipairs, tonumber, type, next = pcall, ipairs, tonumber, type, next
16 local util = require "luci.util"
17 local http = require "luci.http.protocol"
18 local ltn12 = require "luci.ltn12"
19 local table = require "table"
21 module "luci.ttpd.module"
24 -- Server handler implementation
25 Handler = util.class()
28 function Handler.__init__(self)
35 function Handler.setfilter(self, filter, key)
36 self.filters[(key) or (#self.filters+1)] = filter
40 function Handler.setmodifier(self, modifier, key)
41 self.modifiers[(pos) or (#self.modifiers+1)] = modifier
44 -- Creates a failure reply
45 function Handler.failure(self, code, message)
46 local response = Response(code, { ["Content-Type"] = "text/plain" })
47 local sourceout = ltn12.source.string(message)
49 return response, sourceout
52 -- Processes a request
53 function Handler.process(self, request, sourcein, sinkerr)
54 local stat, response, sourceout
56 -- Detect request Method
57 local hname = "handle_" .. request.request_method
60 processor = self[hname],
67 if next(self.modifiers) then
68 for _, mod in util.kspairs(self.modifiers) do
74 stat, response, sourceout = pcall(
75 t.processor, t.handler, t.request, t.sourcein, t.sinkerr
78 -- Check for any errors
80 response, sourceout = self:failure(500, response)
81 elseif next(self.filters) then
84 sourceout = sourceout,
88 for _, filter in util.kspairs(self.filters) do
93 sourceout = t.sourceout
96 response, sourceout = self:failure(405, http.protocol.statusmsg[405])
100 if not util.instanceof(response, Response) then
101 response, sourceout = self:failure(500, "Core error: Invalid module response!")
104 return response, sourceout
108 Response = util.class()
110 function Response.__init__(self, status, headers)
111 self.status = tonumber(status) or 200
112 self.headers = (type(headers) == "table") and headers or {}
115 function Response.addheader(self, key, value)
116 self.headers[key] = value
119 function Response.setstatus(self, status)