2 FFLuCI - 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("ffluci.http", package.seeall)
32 require("ffluci.util")
34 -- Sets HTTP-Status-Header
35 function status(code, message)
36 print("Status: " .. tostring(code) .. " " .. message)
40 -- Asks the browser to redirect to "url"
41 function redirect(url)
43 print("Location: " .. url .. "\n")
47 -- Same as redirect but accepts category, module and action for internal use
48 function request_redirect(category, module, action)
49 category = category or "public"
50 module = module or "index"
51 action = action or "index"
53 local pattern = os.getenv("SCRIPT_NAME") .. "/%s/%s/%s"
54 redirect(pattern:format(category, module, action))
57 -- Form validation function:
58 -- Gets a form variable "key".
59 -- If it does not exist: return "default"
60 -- If cast_number is true and "key" is not a number: return "default"
61 -- If valid is a table and "key" is not in it: return "default"
62 -- If valid is a function and returns nil: return "default"
63 -- Else return the value of "key"
66 -- Get a form variable "foo" and return "bar" if it is not set
67 -- = formvalue("foo", "bar")
69 -- Get "foo" and make sure it is either "bar" or "baz"
70 -- = formvalue("foo", nil, nil, {"bar", "baz"})
72 -- Get "foo", make sure its a number and below 10 else return 5
73 -- = formvalue("foo", 5, true, function(a) return a < 10 and a or nil end)
74 function formvalue(key, default, cast_number, valid, table)
75 table = table or formvalues()
77 if table[key] == nil then
80 local value = table[key]
82 value = cast_number and tonumber(value) or not cast_number and nil
84 if type(valid) == "function" then
86 elseif type(valid) == "table" then
87 if not ffluci.util.contains(valid, value) then
92 return value or default
97 -- Returns a table of all COOKIE, GET and POST Parameters
103 -- Prints plaintext content-type header
104 function textheader()
105 print("Content-Type: text/plain\n")
109 -- Prints html content-type header
110 function htmlheader()
111 print("Content-Type: text/html\n")
115 -- Prints xml content-type header
117 print("Content-Type: text/xml\n")