2 LuCI - HTTP-Interaction
5 HTTP-Header manipulator and form variable preprocessor
14 Copyright 2008 Steven Barth <steven@midlink.org>
16 Licensed under the Apache License, Version 2.0 (the "License");
17 you may not use this file except in compliance with the License.
18 You may obtain a copy of the License at
20 http://www.apache.org/licenses/LICENSE-2.0
22 Unless required by applicable law or agreed to in writing, software
23 distributed under the License is distributed on an "AS IS" BASIS,
24 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 See the License for the specific language governing permissions and
26 limitations under the License.
30 module("luci.http", package.seeall)
32 context = luci.util.threadlocal()
35 Request = luci.util.class()
36 function Request.__init__(self)
44 function Request.formvalue(self, name, default)
45 return self.request[name] or default
48 function Request.formvalues(self)
52 function Request.formvaluetable(self, prefix)
54 prefix = prefix and prefix .. "." or "."
56 for k, v in pairs(self.request) do
57 if k:find(prefix, 1, true) == 1 then
58 vals[k:sub(#prefix + 1)] = v
65 function Request.getenv(self, name)
69 function Request.upload(self, name)
70 return self.uploads[name]
75 if not context.eoh then
80 if not context.closed then
86 function formvalue(...)
87 return context.request:formvalue(...)
90 function formvalues(...)
91 return context.request:formvalues(...)
94 function formvaluetable(...)
95 return context.request:formvaluetable(...)
99 return context.request:getenv(...)
102 function header(key, value)
103 if not context.status then
106 if not context.headers then
109 context.headers[key:lower()] = value
110 coroutine.yield(2, key, value)
113 function prepare_content(mime)
114 header("Content-Type", mime)
117 function status(code, message)
119 message = message or "OK"
120 context.status = code
121 coroutine.yield(1, code, message)
124 function write(content)
125 if not content or #content == 0 then
128 if not context.eoh then
129 if not context.status then
132 if not context.headers or not context.headers["content-type"] then
133 header("Content-Type", "text/html; charset=utf-8")
139 coroutine.yield(4, content)
143 function basic_auth(realm, errorpage)
144 header("Status", "401 Unauthorized")
145 header("WWW-Authenticate", string.format('Basic realm="%s"', realm or ""))
154 function redirect(url)
155 header("Status", "302 Found")
156 header("Location", url)
161 return context.request:upload(...)
166 function build_querystring(table)
169 for k, v in pairs(table) do
170 s = s .. k .. "=" .. v .. "&"
176 function urldecode(str)
177 str = str:gsub("+", " ")
178 str = str:gsub("%%(%x%x)",
179 function(h) return string.char(tonumber(h,16)) end)
180 str = str:gsub("\r\n", "\n")
184 function urlencode(str)
185 str = str:gsub("\n", "\r\n")
186 str = str:gsub("([^%w ])",
187 function (c) return string.format ("%%%02X", string.byte(c)) end)
188 str = str:gsub(" ", "+")