RSP API Reference |
v1.5 - 20-Nov-2010 Nenad Rakocevic
|
REQUEST Object |
content |
access to the HTTP request parameters |
headers |
access to the HTTP request headers |
method |
HTTP request method (GET, POST,...) |
posted |
optional content sent in the HTTP request (POST/PUT data) |
client-ip |
IP address of the client sending the request |
server-port |
server port through which the request was received |
translated |
full path to the resource in the filesystem |
config |
configuration options for the requested domain |
web-app |
web application name |
parsed |
complete HTTP request detailed information |
query-string |
encode request's parameters in URL query-string format |
New store |
save uploaded file |
SESSION Object |
content |
access session variables |
start |
starts a new session |
reset |
reset the initial session context |
end |
destroy the current session |
active? |
test if a session is defined for the current client |
add |
create a new session variable |
remove |
destroy an existing session variable |
exists? |
test if a variable exists in the current session |
id |
session unique identifier |
timeout |
get or set the session timeout value |
Global Functions |
print |
append a value to the response buffer |
probe |
append a molded value to the response buffer |
New emit |
append a reduced value to the response buffer |
include |
load and execute another RSP file |
include-file |
load and output a static file |
validate |
manage a predefined list of request parameters |
html-decode |
convert HTML encoded string to normal text |
html-encode |
convert normal text to HTML encoded string |
url-encode |
encode special URL characters in hexadecimal values |
do-sql |
execute a SQL query on a database |
say |
translate a text in the current language |
?? |
log a variable name followed by its molded value |
? |
shortcut for debug/print |
New debug? |
test if debug mode is active |
|
DB-CACHE Object |
define |
declare the SQL queries to cache |
invalid |
trigger a cache refresh for a given query |
LOCALE Object |
set-lang |
define the current language for translations |
DEBUG Object |
print |
log a debug message |
probe |
log a molded value |
New on |
locally activate the debug mode |
New off |
locally deactivate the debug mode |
New options |
set debug mode options |
|
Request: CONTENT
Syntax
value: request/content/name
name : name of an HTTP parameter passed in the request though GET or POST method.
Description
Gives access to the data sent by the HTTP client through a GET or POST request to the server. Values are always returned as string! values. request/content is a simple block! of name/value pairs filled just before the execution of the RSP page, so it can also be processed using a loop.
Note: Trying to use a name that doesn't match any parameter name sent in the request will result in an error!. If you're not sure about the presence of a given parameter in the request, you can use find or select to check its presence in request/content before accessing it.
Example
HTTP request: GET /test.rsp?id=5&mode=full
test.rsp : <% print [request/content/id request/content/mode] %>
will output : 5 full
HTTP request: GET /test.rsp?id=5&mode=full
test.rsp : <% print either find request/content 'type ["found"]["not found"] %>
will output : not found
HTTP request: GET /test.rsp?id=5&mode=full&action=save
test.rsp : <% probe request/content %>
will output : [id "5" mode "full" action "save"]
Request: HEADERS
Syntax
value: request/headers/name
name : name of an HTTP header passed in the request.
Description
Gives access to the headers sent by the HTTP client in the request. Values are always returned as string! values. headers is a simple block! of name/value pairs filled just before the execution of the RSP page, so it can also be processed using a loop.
Note: Trying to use a name that doesn't match any parameter name sent in the request will result in an error!. If you're not sure about the presence of a given parameter in the request, you can use find or select to check its presence in request/headers before accessing it.
Example
HTTP request: GET /test.rsp
Host: domain.com
User-Agent: Mozilla
Connection: keep-alive
test.rsp : <% print request/headers/user-agent %>
will output : Mozilla
HTTP request: GET /test.rsp
Host: domain.com
User-Agent: Mozilla
Connection: keep-alive
test.rsp : <%
either value: select request/headers 'User-Agent [
print value
][
print "unknown"
]
%>
will output : Mozilla
Request: METHOD
Syntax
value: request/method
returns a word! value.
Description
Returns the HTTP method used in the request. The most used methods are HEAD, GET and POST.
Example
HTTP request: GET /test.rsp
test.rsp : <% probe request/method %>
will output : GET
Request: POSTED
Syntax
value: request/posted
returns a binary! value.
Description
Returns the data POST-ed by the client. Notice that other HTTP methods, like PUT can carry data.
(Todo: explain how multipart data is handled)
Example
HTTP request: POST /test.rsp
Host: domain.com
Hello World!
test.rsp : <% probe to-string request/posted %>
will output : "Hello World!"
Request: CLIENT-IP
Syntax
value: request/client-ip
returns a tuple! value.
Description
Returns the IP address of the client sending the request.
Example
HTTP request: from 1.2.3.4
test.rsp : <% print request/client-ip %>
will output : 1.2.3.4
Request: SERVER-PORT
Syntax
value: request/server-port
returns an integer! value.
Description
Returns the server port-id receiving the request.
Example
HTTP request: http://domain.com:4000/test.rsp
test.rsp : <% print request/server-port %>
will output : 4000
Request: TRANSLATED
Syntax
value: request/translated
returns a file! value.
Description
Returns the full path to the resource in the filesystem.
Example
HTTP request: http://domain.com/test.rsp
test.rsp : <% probe request/translated %>
will output : %/usr/local/domain.com/www/test.rsp
Request: CONFIG
Syntax
value: request/config
returns a block! value.
Description
Returns the configuration options for the requested domain, loaded from the HTTP.CFG file.
Example
HTTP request: http://domain.com/test.rsp
test.rsp : <% probe request/config %>
will output : [
root-dir %/usr/local/domain.com/www/
default [%index.rsp index.html]
]
Request: WEB-APP
Syntax
value: request/web-app
returns a string! value.
Description
If the requested resource is contained in a web-app, it returns the web-app name, else it returns none.
Example
HTTP request: http://domain.com/myapp/test.rsp
test.rsp : <% probe request/web-app %>
will output : "/myapp"
Request: PARSED
Syntax
value: request/parsed
returns an object! value.
Description
Returns an object containing the complete detailed information from the parsed HTTP request. Some of these information have shortcut accessors from the
request object.
PARSED Object attributes :
Attribute |
Description |
Type |
headers |
HTTP request headers |
block! |
status-line |
first line of the HTTP request |
string! |
method |
HTTP method |
word! |
url |
requested URL |
string! |
content |
POST-ed data |
binary! or none! |
path |
URL path part |
string! or none! |
target |
URL resource part |
string! or none! |
arg |
URL argument part (after # or ?) |
string! or none! |
ext |
URL resource suffix part |
word! or none! |
version |
HTTP request protocol version |
string! |
file |
request's URI (path and target only) |
string! or none! |
Example
HTTP request: GET /myapp/test.rsp?id=123 HTTP/1.0
Host: domain.com
User-Agent: Mozilla
test.rsp : <% probe request/parsed %>
will output : make object! [
headers: [Host "domain.com" User-Agent "Mozilla"]
status-line: "GET /myapp/test.rsp?id=123 HTTP/1.0^/^M"
method: GET
url: "/myapp/test.rsp?id=123"
content: none
path: "/myapp/"
target: "test.rsp"
arg: "?id=123"
ext: .rsp
version: "1.0"
file: "/myapp/test.rsp"
]
Request: QUERY-STRING
Syntax
value: request/query-string
returns an string! value.
Description
Returns a re-composed query-string from the request parameters (REQUEST/CONTENT names and values). It you didn't altered the request parameters, it gives you the initial query-string received from the client.
Example
HTTP request: http://test.rsp?a=1&b=hello
test.rsp : <%
print request/query-string
request/content/b: none
print request/query-string
%>
will output : a=1&b=hello
a=1
Request: STORE
Syntax
request/store file-spec
request/store/as file-spec path
file-spec : uploaded file definition block! as passed in request/content.
path : location where to save the file, with optional filename.
Description
Cheyenne has an efficient way to handle uploaded files or large POSTed data: it streams them to a disk file instead of keeping them whole in memory. So, from the RSP script perpective, the upload file appears as a block! composed of:
- the original uploaded filename
- the path to a temporary file holding the content
This specification block is accessible through
request/content/<param> where
param is the name used in the HTML
<input type="file">, element and when the form use a
enctype="multipart/form-data" encoding type. If no encoding type is provided, the whole data passed as POST or PUT will be streamed to disk and a default
file parameter name will be forced by Cheyenne.
So, when a file is uploaded, the file content is saved on disk using a temporary filename (for security concerns). This temporary file is deleted just after the RSP script execution.
Request/store gives you an handy way to save this file from deletion, by using a internal "move" method when possible, or using a system call as fallback (the "move" operation is done in constant time whatever the file size is).
The default behaviour is to save the file to its original name in the incoming folder (used for all temporary files). The
/as refinement allows you to specify a target folder and, optionaly, a target file name (to override the original file name).
Warning: it's recommended to check the file name suffix for all uploaded files to avoid security breaches, especially if the target file can be run by Cheyenne (like .rsp, .cgi, .php, ...). The best way to protect your site from that risk, is to store the files with server-generated names instead of original ones, and save the old/new names associations somewhere (in a file or database).
Notes:
-
Cheyenne stores temporary files in a default folder named %incoming/ (so, relative to Cheyenne home folder). This folder can be changed using the config keyword incoming-dir (in domain or webapp config sections of %httpd.cfg file) followed by the path to the new incoming folder.
-
Cheyenne accepts by default uploaded file size up to 2GB. This can be lowered by the (per domain or webapp) post-max config keyword followed by the maximum POST/PUT accepted data size.
-
For data sent to Cheyenne without the multipart/form-data encoding, the uploaded data is held in memory until a threshold size is reached, then it is streamed on disk. The default threshold value is 100KB. It can be set to any value up to 2GB using the config keyword post-mem-limit followed by the threshold value.
Example
HTTP request: http://domain.com/test.html
test.html : ...
<form target="test.rsp" method="post" enctype="multipart/form-data">
<input type="file" name="myphoto">
<input type="submit" name="submit" value="Upload">
</form>
...
test.rsp : <%
probe file: request/content/myphoto
request/store/as file %/home/www/pictures/
print exists? %/home/www/pictures/john.jpg
%>
will output : ["john.jpg" %/usr/cheyenne/incoming/fgffdkwd.tmp]
true
Session: CONTENT
Syntax
value: session/content/name
session/content/name: value
name : name of an existing session variable.
Description
The CONTENT block allows access to all session values in read/write mode.
The session variables must be declared, with SESSION/ADD before being used.
Example
HTTP request: GET /test.rsp
test.rsp : <%
session/add 'count 0
session/content/count: session/content/count + 1
%>
HTTP request: GET /count.rsp
count.rsp : <%
print session/content/count
%>
will output : 1
Session: START
Syntax
value: session/start
Returns TRUE if a session is already active, else FALSE.
Description
Start a new session for the current client. If a session is already running, this function won't have any effect.
Note: the ON-SESSION-START event for webapps, won't be called in this case.
Example
HTTP request: GET /test.rsp
test.rsp : <%
unless session/start [
session/add 'count 1
]
%>
HTTP request: GET /count.rsp
count.rsp : <%
either session/active? [
print session/content/count
][
print "No session"
]
%>
will output : 1
Session: RESET
Syntax
session/reset
Description
Reset the session environment in WebApps. session/login? is set to FALSE and the ON-SESSION-START event is called. It's useful for resetting the session variables while maintaining the session.
Note: if it's used outside of a WebApp context, it has no effect.
Example
HTTP request: GET /change-user.rsp
change-user.rsp : <%
session/reset
response/redirect "login.rsp"
%>
Session: END
Syntax
session/end
Description
Destroy the current session if exists. All variables and values associated are lost.
Example
HTTP request: GET /logout.rsp
logout.rsp : <% session/end %>
Session: ACTIVE?
Syntax
value: session/active?
returns a logic!value.
Description
Returns TRUE if a session is currently active for the current user, otherwise FALSE.
Example
HTTP request: GET /test.rsp
test.rsp : <%
if not session/active? [
session/start
]
%>
Session: ADD
Syntax
session/add name value
name : new word to add to the session (word!).
value : initial value of the word (any-value!)
Description
Creates a new variable in the session context. This variable and its value will persist while the session is active or until you remove it.
Note: Remember that storing data in sessions takes resources and can have a negative impact on the performances of the RSP pages. Keep it as lightweight as possible.
Example
HTTP request: GET /test.rsp
test.rsp : <%
session/add 'hit 1
%>
HTTP request: GET /count.rsp
count.rsp : <%
print session/content/hit: session/content/hit + 1
%>
will output : 2
Session: REMOVE
Syntax
session/remove name
name : word to remove from the session (word!)
Description
Removes a variable from the session context.
Example
HTTP request: GET /test.rsp
test.rsp : <%
if session/exists? 'hit [
session/remove 'hit
print "HIT variable removed"
]
%>
will output : HIT variable removed (if 'hit was defined in the session)
Session: EXISTS?
Syntax
value: session/exists? name
name : word to test (word!)
returns a logic! value.
Description
Returns TRUE if a variable is defined in the current session, otherwise FALSE.
Example
HTTP request: GET /test.rsp
test.rsp : <%
print session/exists? 'hit
%>
will output : true (if 'hit is defined in the session)
Session: ID
Syntax
value: session/id
returns a string! value.
Description
Returns the unique session ID. This ID is used to maintain the session alive and bind it to the user by passing it in a session cookie.
Note: if a session is started using SESSION/START, and in the same RSP, you try to read the ID property, it will return none.
Example
HTTP request: GET /test.rsp
test.rsp : <%
if session/active? [
print session/id
]
%>
will output : <a_string_of_24_capital_letters> (if a session is active)
Session: TIMEOUT
Syntax
value: session/timeout
session/timeout: new
new : new timeout value for the current session (time!)
returns a time! value.
Description
Sets or returns the session timeout value. This value define the maximum idle time before the session expires (idle time is defined as the time between two requests to the server from the same user).
Note: a session default timeout is defined by the 'timeout keyword in HTTPD.CFG config file in webapp or domain sections. If it's not explicitly defined anywhere, a default value of 20 minutes is used.
Example
HTTP request: GET /test.rsp
test.rsp : <%
if session/active? [
print ["Old value =" session/timeout]
session/timeout: 01:00:00 ;-- set timeout to 1 hour
print ["New value =" session/timeout]
]
%>
will output : Old value = 00:20 (if a session is active)
New value = 01:00
Global: PRINT
Syntax
print value
value: value to output (any-value!)
Description
Appends a REFORM-ed value to the response buffer.
Note: print is the function counterpart of <%= ... %> RSP construct.
Example
HTTP request: GET /test.rsp
test.rsp : <% print ["date:" now/date] %>
will output : date: 20-Nov-2010 ;-- notice the additional space
Global: PROBE
Syntax
probe value
value: value to mold and output (any-value!)
Description
Appends a MOLD-ed value to the response buffer.
Example
HTTP request: GET /test.rsp
test.rsp : <% probe "value" %>
will output : "value"
Global: EMIT
Syntax
emit value
value: value to reduce and output (any-value!)
Description
Appends a REDUCE-ed value to the response buffer, it's a shortcup for a REPEND-like action.
Note: emit is the function counterpart of <%? ... %> RSP construct.
Example
HTTP request: GET /test.rsp
test.rsp : <% emit ["date: " now/date ", time: " now/time] %>
will output : date: 20-Nov-2010, time: 18:01
Global: INCLUDE
Syntax
include filename.rsp
filename.rsp : RSP file to execute (file!)
Description
Loads and executes an RSP file, the generated output will be append to the current response buffer. This is useful to share common RSP code between several pages. For example, you could include dynamic header and footer with RSP code in all your pages using this function.
Note: you can recursively include a maximum of 5 RSP files, more than that would be insane ;-). This prevents from infinite cycles issues.
Example
HTTP request: GET /footer.rsp
footer.rsp : <span>
<% include %time.rsp %>
</span>
time.rsp : <%= now/time %>
will output : <span>
19:28:15
</span>
Obviously, this is an academic example, it's really useful when you need to share a lot of code.
Global: INCLUDE-FILE
Syntax
include-file filename
filename : static file to include (file!)
Description
Loads and includes a static file (usually, it's an HTML file) by appending its content to the response buffer. No processing is done on the file. This is useful to share common HTML parts between several pages. For example, you could include a static header and footer in all your pages using this function.
Example
HTTP request: GET /test.rsp
test.rsp : ...HTML or RSP code...
<% include-file %footer.inc %>
footer.inc : </body>
</html>
will output : ...HTML or RSP code...
</body>
</html>
Global: VALIDATE
Syntax
value: validate specs
value: validate/full specs
specs : list of parameters with constraints (block!)
returns a block! or none! value.
specs dialect syntax (no refinement) organized in 2 columns:
(1st col) (2nd col)
[
name datatype! or -
...
]
specs dialect syntax (/full) organized in 3 columns:
(1st col) (2nd col) (3rd col)
[
name datatype! or - * or -
...
]
specs columns syntax:
1st column : word!
2nd column : - or a REBOL datatype!
and optionally :
3rd column : *, - or a default value
Description
It's often unsafe to access a request parameter by using the following :
request/content/name, if
name hasn't been passed in the request, this expression will raise an error!.
The VALIDATE function is a handy way to pre-process the REQUEST/CONTENT block of parameters received from the client. The provided dialect lets you validate parameters by :
- Ensuring that the parameter is present (by adding it with none! value, if required)
- Casting the parameter to a given datatype
- Adding a mandatory attribut
To define the required
specs block, list all the parameters names you want to process, then define the target REBOL datatype, and optionally, add a mandatory attribut.
When the validation process is completed, the function returns a
none! value indicating that all constraints are fulfilled, or a
block! value listing all the parameter names that failed one or several tests.
Note:
-
The REQUEST/CONTENT values could be modified (converted to the required datatype) in the process, so if you use VALIDATE partially on a few parameters, then later, apply again VALIDATE on the other parameters, be sure to make separated list of parameters, don't validate twice the same parameter, it might generate false validation results.
-
If a value is use as third argument (with /full refinement), the parameter, if missing, will be set to that default value.
Example
HTTP request: GET /test.rsp?a=123&b=456
test.rsp : <%
probe request/content
probe validate [
a integer!
b - ; minus means don't process, so, string! result
]
probe request/content
%>
will output : [a "123" b "456"]
none
[a 123 b "456"]
HTTP request: GET /test.rsp?a=123&b=456
test.rsp : <%
probe request/content
probe validate [
a integer!
b word!
c - ; c is not present, so it will be just added
]
probe request/content
%>
will output : [a "123" b "456"]
[b]
[a 123 b "456" c none]
HTTP request: GET /test.rsp?a=123&b=456
test.rsp : <%
probe request/content
probe validate/full [
a integer! *
b integer! -
]
probe request/content
%>
will output : [a "123" b "456"]
none
[a 123 b 456]
HTTP request: GET /test.rsp?b=456
test.rsp : <%
probe request/content
probe validate/full [
a integer! * ; a is not present, but mandatory !
b integer! -
c integer! 123 ; c is optional with a default value
]
probe request/content
%>
will output : [b "456"]
[a]
[a none b 456 c 123]
Global: HTML-DECODE
Syntax
value: html-decode data
data : HTML encoded text (string!, binary!)
returns a string! value.
Description
Processes a text buffer and converts HTML entities to characters. It returns a new string! value.
Note: HTML-DECODE current implementation only support entities defined in ISO-8859-1 (Latin1) encoding.
Example
HTTP request: GET /test.rsp
test.rsp : <%= html-decode "<tag>" %>
will output : <tag>
Global: HTML-ENCODE
Syntax
value: html-encode data
data : normal text (string!, binary!)
returns a string! value.
Description
Processes a text buffer and converts all specials characters to HTML entities. It returns a new string! value.
Note: HTML-ENCODE current implementation only support entities defined in ISO-8859-1 (Latin1) encoding.
Example
HTTP request: GET /test.rsp
test.rsp : <%= html-encode "<tag>" %>
will output : <tag>
HTTP request: GET /test.rsp
test.rsp : <%= html-decode html-encode "<tag>" %>
will output : <tag>
Global: URL-ENCODE
Syntax
value: url-encode data
value: url-encode/all data
data : URL or text that need to be passed in URL (string!)
returns a string! value.
Description
Processes a text buffer and converts all specials URL characters to hexadecimal values. It returns a new string! value. This encoding is required if you build an URL dynamically.
/ALL refinement will apply more aggressive encoding (all URL reserved characters will be encoded too).
Example
HTTP request: GET /test.rsp
test.rsp : <%=
link: "http://domain.com/target.rsp?var=This is a test"
url-encode link
%>
will output : http://domain.com/target.rsp?var=This%20is%20a%20test
HTTP request: GET /test.rsp
test.rsp : <%=
link: "http://domain.com/target.rsp?var=This is a test"
url-encode/all link
%>
will output : http%3A%2F%2Fdomain.com%2Ftarget.rsp%3Fvar%3DThis%20is%20a%20test
Global: DO-SQL
Syntax
value: do-sql db query
value: do-sql/flat db query
db : a db connection name defined in the config file (word!)
query : the SQL query or cached query name to execute (string!, block! or word!)
returns a block! or none! value.
Description
Preliminary Notice: The usage of DO-SQL is tight to the databases connections definitions specified in you HTTPD.CFG configuration file. If the databases section is not defined, DO-SQL would be useless. Here's an example of such configuration :
globals [
...
databases [
bugs postgres://root@localhost/bugs
forum mysql://root:admin@localhost/forum
test odbc://testdsn
...
]
...
]
So, DO-SQL is a higher level function allowing you to access your databases in a consistant way, whatever database drivers you're using (from
RT,
Softinnov, 3rd party...) as long as the driver is embedded in a REBOL scheme handler and supports the basic port operation (open, insert, copy, pick, close).
The main principle of using DO-SQL is that all the connection's opening, re-opening and closing actions are taken in charge by the RSP engine. So, you can assume that all connections are always available and ready to use. DO-SQL will smartly handle the connections so that they will be opened only on the first use. It's all transparent for the RSP developer. By the way, the Cheyenne multi-processes architecture naturally generates a pool of databases connections, so using DO-SQL ensures that you have a clean and scalable database connection model.
DO-SQL supports direct querying using SQL statements defined as string or prepared statement using a block value specification (see your database driver's documentation). DO-SQL also supports cached query names provided by the DB-CACHE object.
DO-SQL returns a recordset of values resulting from the query or a
none! value if the query hasn't produced any result (like SQL INSERT or UPDATE).
The /FLAT refinement is available for all drivers and will return a flat recordset (one block of all the records values).
Example
HTTP request: GET /test.rsp
test.rsp : <%
print do-sql 'bugs "show tables"
print do-sql/flat 'bugs "show tables"
%>
will output : [["table1"]["table2"]["table3"]...]
["table1" "table2" "table3"...]
HTTP request: GET /test.rsp
test.rsp : <%
db-cache/define [
tables "show tables"
]
...
print do-sql 'bugs 'tables
%>
will output : [["table1"]["table2"]["table3"]...]
HTTP request: GET /add-user.rsp?name=John%20Doe&age=33
add-user.rsp :
<%
either invalid: validate/full [
name - *
age integer! -
][
print ["Error: missing or incorrect parameter(s) " invalid]
][
do-sql 'bugs ["INSERT INTO users VALUES (?,?)" name age]
print ["New user added:" request/content/name]
]
%>
will output : New user added: John Doe
Global: SAY
Syntax
value: say text
text : text to translate (string!)
returns a string! value.
Description
Translates the text passed in argument using the current language definition. If the corresponding translation is not found, the text is passed unchanged.
Notes:
- The translation matching is case-sensitive !
- The default language is 'en (english). To define another language as default, use the 'default-lang directive in HTTPD.CFG file (e.g. default-lang 'fr)
Example
in %catalogs/en/en.cat :
"Hello"
"we are in"
"January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"
in %catalogs/fr/fr.cat :
"Bonjour"
"nous sommes en"
"Janvier"
"F�vrier"
"Mars"
"Avril"
"Mai"
"Juin"
"Juillet"
"Ao�t"
"Septembre"
"Octobre"
"Novembre"
"D�cembre"
in %httpd.cfg :
...
locales-dir %catalogs/
...
HTTP request: GET /test.rsp
test.rsp : <%
print say "Hello"
locale/set-lang 'fr
print say "Hello"
print reform [
say "we are in"
say pick system/locale/months now/month
]
%>
will output : Hello
Bonjour
nous sommes en juillet
Global: ??
Syntax
?? word
word: word value to log in trace file (word!)
Description
Log the word symbol and its MOLDed value to %trace.log debug file. It works like its REBOL mezzanine counterpart. This file is stored in your Cheyenne main folder.
Note: this command will work even if your webapp is in production state (means no DEBUG keyword in the webapp config section).
Example
HTTP request: GET /test.rsp?action=search
test.rsp :
<%
either find request/content 'action [
type: 1
...
][
type: 0
...
]
?? type
%>
will output in %trace.log :
...
28/2-19:50:28.687-[DEBUG] type: 1
...
Global: DEBUG?
Syntax
value: debug?
Returns TRUE if debug mode is active else FALSE.
Description
This is a simple way to know if the current RSP script is under debug mode or not. It can be handy in order to display additional debug messages on screen or in trace log file.
Example
HTTP request: GET /test.rsp?name=john
test.rsp : <%
validate [name -]
list: do-sql 'shop [
"SELECT * FROM books WHERE author=?"
request/content/name
]
if debug? [debug/probe list] ;-- outputs query results in trace file
%>
Response: BUFFER
Syntax
value: response/buffer
response/buffer: data
data : data to send to client (string!, binary!, file!)
returns a string! value.
Description
Directly access the RESPONSE buffer. This buffer is normaly filled by all the HTML template code from the executed RSP and by all the printing REBOL functions used in RSP pages. This property allows you to do any pre or post-processing on the generated page. It also allows you to generate the resulting buffer using other method than executing RSP code.
Setting response/buffer to a file! value is a powerful way to send back a static file to the client as a result of the RSP script without having to load it first in memory. Cheyenne will take care of sending the file in a streamed way to minimize memory usage. Be sure to use an absolute path for the file! value, else Cheyenne might not find it and the clent will get a 404 HTTP code instead. The mime type will be set by Cheyenne depending on the file extension, or you can force it using a content-disposition header.
Example
HTTP request: GET /test.rsp
test.rsp : <%
image: make binary! 10'000
img: draw 100x100 [line 0x0 99x99]
save/png image img
response/buffer: image
response/set-header 'Content-type "image/png"
%>
will output : <binary data of the generated image>
HTTP request: GET /test.rsp
test.rsp : <%
response/buffer: get-modes %file123.tmp 'full-path
response/set-header 'Content-Disposition {attachment; filename="movie123.avi"}
%>
will output : Content-Disposition: attachment; filename="movie123.avi"
<binary data of the movie file>
Response: SET-STATUS
Syntax
response/set-status code
response/set-status/msg code message
code : HTTP status return code (3 digits integer!).
message : Text message describing the status that will appear in
the first line of the HTTP response. (String!)
Description
Forces the HTTP return code and optionally, specify the text message for the returned status line. Note that, by default, Cheyenne will only use the following return codes : 200, 404, 501. You can override theses codes by using SET-STATUS.
The optional message is mostly useful in case of error codes, it should be displayed the client browser along with the error codes, giving you the opportunity to respond with a more accurate error message than the default one.
Example
HTTP request: GET /test.rsp
test.rsp : <% response/set-status 403 %>
will return : HTTP/1.1 403 Forbidden
...
HTTP request: GET /test.rsp
test.rsp : <% response/set-status/msg 403 "Access Restricted"%>
will return : HTTP/1.1 403 Access Restricted
...
Response: SET-HEADER
Syntax
response/set-header name value
name : HTTP header name (word!)
value : Header value (string!, none!)
Description
Define HTTP headers' values. Giving a none! value will ensure that the header won't be sent with the response. This can be useful in many cases, like outputting a binary content (Image, PDF,...) instead of HTML content.
Cheyenne defines its own HTTP headers for the response, but the user-defined headers will prevail over Cheyenne's default ones.
Example
HTTP request: GET /test.rsp
test.rsp : <%
response/set-header 'Powered-by "REBOL"
%>
will return : HTTP/1.1 200 OK
Date: Sun, 18 Feb 2007 15:15:12 GMT
Server: Cheyenne/0.9.9.0
Content-Type: text/html
Content-Length: 682
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Connection: close
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Powered-by: REBOL
HTTP request: GET /test.rsp
test.rsp : <%
response/set-header 'Server "cheyenne"
response/set-header 'Cache-control none
response/set-header 'Expires none
%>
will return : HTTP/1.1 200 OK
Date: Sun, 18 Feb 2007 15:15:12 GMT
Server: cheyenne
Content-Type: text/html
Content-Length: 682
Connection: close
Pragma: no-cache
Response: END
Syntax
response/end
Description
Abort the RSP execution and send the response buffer back to the client.
Example
HTTP request: GET /test.rsp?err=123
test.rsp : <html>
<body>
<% if find request/content 'err [
print [
"Error code:" request/content/err
</body>
</html>
]
response/end
]
%>
<h1> Displayed if no error</h1>
...
</body>
</html>
will return : <html>
<body>
Error code: 123
</body>
</html>
Response: RESET
Syntax
response/reset
Description
Clears the response buffer.
Note: it doesn't break RSP execution.
Example
HTTP request: GET /test.rsp?value=1
hello.xml: <say>Hello</say>
test.rsp : <html>
<body>
<% switch/default select request/content 'value [
1 [
response/reset
response/set-header 'Content-Type "text/xml"
include-file %hello.xml
response/end
]
2 [
print "Text..."
]
][
...
]
%>
...
</body>
</html>
will return : HTTP/1.1 200 OK
Content-Type: text/xml
Content-Length: 16
...
<say>Hello</say>
In this example, RESET is used to clear the HTML already in the buffer,
to be able to send back an image instead of HTML code.
Response: REDIRECT
Syntax
response/redirect url
response/redirect/strict url
response/redirect/thru url
response/redirect/last url
url : Target URL (url!, string!).
Description
Returns a HTTP redirection code 302 to the client asking it to jump to the target URL using a GET or HEAD method.
The /strict option produces a 303 return code, meaning that's a temporary redirection. A GET request will be issued by the client for retrieving the target URL.
The /thru option will return a HTTP code 307 asking the client to use the same HTTP method for requesting the target URL. An initial POST request will result, after the redirection, in a POST request to the target URL (as required by the HTTP v1.1 protocol).
The /last option will return a HTTP code 301 meaning that the resource has moved permanently.
Note: it does automatically exit the RSP script.
Example
HTTP request: GET /test.rsp?action=1
test.rsp : <%
switch select request/content 'action [
1 [response/redirect "/main.html"]
2 [response/redirect "/login.rsp"]
3 [response/redirect http://www.rebol.com]
]
%>
<html>
<body>
...
</body>
</html>
will return : HTTP/1.1 302 Moved Permanently
Location: /main.html
...
Response: FORWARD
Syntax
response/forward url
url : Target URL (url!, string!).
Description
Stops the execution of the RSP and forwards the request to a new URL. RESPONSE/BUFFER will be cleaned before making the jump. The
url argument have to be either a full URL with an explicit target or an absolute path to a target within the same host. All initial request parameters passed in GET or content passed in POST and all headers will be also forwarded to the new URL.
Note:
-
Cheyenne allows a maximum of 3 forwards for the same requests. This is done to avoid being caught in an infinite forwarding loop.
-
Using FORWARD when the page is in not-buffered mode is forbidden and will raise an error!. Not-buffered mode is entered when RESPONSE/FLUSH is used.
Example
HTTP request: GET /forward.rsp?var=1
forward.rsp :
<% response/forward "/test.rsp" %>
<html>
<body>
This part will never be sent to the client!
</body>
</html>
test.rsp : Result is <%=request/content/var%>
will output : Result is 1
Response: FLUSH
Syntax
response/flush
Description
Sends the current response buffer back to the client. The response buffer is then reset and the RSP execution continues. It's a way to stream data to the client without waiting to end of RSP execution.
Example
HTTP request: GET /test.rsp
test.rsp :
<table>
<% loop 100 [ %>
<tr><td><%= random 100 %></td></tr>
<%
response/flush
]%>
</table>
will return : HTTP/1.1 200 OK
...
<table>
<tr><td>12</td></tr> <-- sent after 1st flush
<tr><td>47</td></tr> <-- sent after 2nd flush
<tr><td>23</td></tr> <-- sent after 3rd flush
... ...
</table>
Response: NO-LOG
Syntax
response/no-log
Description
By default, all requests generate an entry in the HTTP log file when the response is sent to the client. NO-LOG tells the engine to not write an entry in the log file for the current request only.
Example
HTTP request: GET /test.rsp
test.rsp :
<% response/no-log %>
Response: NO-COMPRESS
Syntax
response/no-compress
Description
By default, RSP response output is compressed (using the deflate algorithm) before being sent back to the client, if the client supports such compression (declared by client using the Accept-Encoding header). NO-COMPRESS tells the engine to not compress output for the current request only.
Example
HTTP request: GET /test.rsp
test.rsp :
<% response/no-compress %>
<h1>Hello world!</h1>
will return : HTTP/1.1 200 OK
...
<h1>Hello world!</h1>
test2.rsp :
<h1>Hello world!</h1>
will return : HTTP/1.1 200 OK
Content-Encoding: deflate
...
F348CDC9C95728CF2FCA495104001D09045E
Event: ON-RSP-START
Syntax
on-rsp-start [DEPRECATED]
Description
Replaced by WORKER-LIBS config option.
Example
Event: ON-RSP-END
Syntax
on-rsp-end [DEPRECATED]
Description
Replaced by WORKER-LIBS config option.
Example
Event: ON-APPLICATION-START
Syntax
on-application-start: does [...]
Defined in %www/web-app/app-init.r
Description
This event will only be generated when used in a web application context.
Event called when the web application is first used in a given background process. It's a good place to load application-specific code and data (like a configuration or preferences file).
Example
on-application-start: does [
do %private/config.conf
do %private/helper.r
do %private/captcha.r
captcha/set-fonts-path %private/fonts/
]
Event: ON-APPLICATION-END
Syntax
on-application-end: does [...]
Defined in %www/web-app/app-init.r
Description
This event will only be generated when used in a web application context.
Event called when a background process die. This event allows you to unload, if required, some libraries and free some external dependencies that are specific to your application and usually initialized in ON-APPLICATION-START.
Note: REBOL will free almost all open resources for you, so, you should use this event only for closing or releasing resources that require specific handling.
Example
on-application-start: does [
libc: load/library %libc5.so
]
on-application-end: does [
free libc
]
Event: ON-SESSION-START
Syntax
on-session-start: does [...]
Defined in %www/web-app/app-init.r
Description
This event will only be generated when used in a web application context.
Event called when the web application session is started. It's a good place to initialize all your session variables.
Note: The SESSION/START function won't generate this event, but SESSION/RESET will.
Example
on-session-start: does [
session/add 'user "guest"
session/add 'hits 1
]
Event: ON-PAGE-START
Syntax
on-page-start: does [...]
Defined in %www/web-app/app-init.r
Description
This event will only be generated when used in a web application context.
Event called just before a RSP is executed.
Example
on-page-start: does [
set 'start-time now/time/precise
]
Event: ON-PAGE-END
Syntax
on-page-end: does [...]
Defined in %www/web-app/app-init.r
Description
This event will only be generated when used in a web application context.
Event called just after a RSP has been executed.
Example
on-page-start: does [
set 'start-time now/time/precise
]
on-page-end: has [pos elapsed][
if pos: find response/buffer "</body>" [
elapsed: now/time/precise - start-time
insert pos reform ["<br>Processed in :" elapsed]
]
DB-Cache: DEFINE
Syntax
db-cache/define db specs
db: database connection name (word!)
specs: list of SQL queries to cache (block!)
specs syntax:
[
name (word!) query (string!)
...
]
Description
Declares the list of SQL queries to be cached in memory for a given connection name. The database connection name have to match one of those defined in the "databases" section in the HTTPD.CFG file.
Note: Currently, only static requests can be cached, this may be improved in future version to also cache dynamically composed queries.
Example
on-session-start: does [
db-cache/define 'bugs [
priorities "SELECT id,label FROM priorities"
roles "SELECT id,label FROM roles"
projects "SELECT * FROM projects WHERE id > 1"
priv-proj "SELECT id, name FROM projects WHERE private=1"
pub-proj "SELECT id, name FROM projects WHERE private=0"
]
]
HTTP request: GET /test.rsp
test.rsp :
<%
probe do-sql/flat 'bugs 'priorities
%>
will output : ["none" "low" "medium" "high"]
DB-Cache: INVALID
Syntax
db-cache/invalid db name
db: database connection name (word!)
name: cached SQL query name or list of names (word!, block!)
Description
Forces the cache manager to refresh the query (or queries) next time they will be used. The database connection name have to match one of those defined in the "databases" section in the HTTPD.CFG file.
Example
db-cache/invalid 'bugs 'priorities
db-cache/invalid 'bugs [
projects
priv-proj
pub-proj
]
Locale: SET-LANG
Syntax
locale/set-lang id
id: language identifier (word!)
Description
Defines the current language for translations done by the
SAY function or statically embedded using the #[...] notation. The language
id format is the standard one used by web browsers and transmitted to servers using the 'Accept-Language HTTP header. These ids are formatted as xx or xx-yy. Examples: fr, en, fr-FR, en-US,...
Note: If this function is not called, the following sequence will be executed to determine the appropriate language :
- Use the session/content/lang value if defined
- Use the language ID found in the Accept-Language header
- Use the default language defined in HTTPD.CFG file
- Use 'en (if 'en locale catalog file is not found, no translation will occur)
Example
HTTP request: GET /test.rsp
test.rsp : <% locale/set-lang 'fr %>
See the
SAY function documentation for a complete example.
Debug: PRINT
Syntax
debug/print value
value: value or message to log in trace file (any-value!)
Description
Log a message or an evaluated value to %trace.log debug file. This file is stored in your Cheyenne main folder.
Note: this command will work even if your webapp is in production state (means no DEBUG keyword in the webapp config section).
Example
HTTP request: GET /test.rsp?action=search
test.rsp :
<%
if find request/content 'action [
debug/print ["action :" request/content/action]
...
]
%>
will output in %trace.log :
...
28/2-19:50:28.687-[DEBUG] action : search
...
Debug: PROBE
Syntax
debug/probe value
value: value to log in trace file (any-value!)
Description
Log a MOLDed value to %trace.log debug file and returns the same value. This file is stored in your Cheyenne main folder.
Note: this command will work even if your webapp is in production state (means no DEBUG keyword in the webapp config section).
Example
HTTP request: GET /test.rsp?action=search
test.rsp :
<%
if debug/probe found? find request/content 'action [
debug/probe request/content
...
]
%>
will output in %trace.log :
...
28/2-19:50:28.687-[DEBUG] true
28/2-19:50:28.688-[DEBUG] [action "search"]
...
Debug: ON
Syntax
debug/on
Description
If the debug mode is not set in the config file for the current domain or webapp, this function will force the debug mode, but only for the current RSP script.
Example
HTTP request: GET /test.rsp?trace=1
test.rsp : <%
validate/full [trace integer! 0]
if request/content/trace = 1 [
debug/on
]
%>
will output : <HTML output with the RSP debug bar on top >
Debug: OFF
Syntax
debug/off
Description
If the debug mode is set in the config file for the current domain or webapp, this function will switch off the debug mode, but only for the current RSP script.
Example
HTTP request: GET /test.rsp?trace=0
test.rsp : <%
validate/full [trace integer! 1]
if request/content/trace = 0 [
debug/off
]
%>
will output : <HTML output without any debug bar or error popup >
Debug: OPTIONS
Syntax
debug/options [specs]
specs: name/value pairs. Possible options are:
o lines: integer! number of lines from the trace file to display
o colors: [word! word!] font and background colors for trace file display
o error: 'popup | 'inline controls how RSP errors are displayed
o ip: tuple! restricts debug mode to requests coming from this address only
Description
Changes default settings for debug mode.
Lines and
colors apply to the trace file display accessible from the debug bar.
Error controls if RSP errors are to be displayed inlined in the HTML page flow or in a popup overlay style. The
ip option turns on the debug mode only for a given client IP address, allowing the site owner to debug issues on a RSP script in production without disturbing users. Default values are :
- lines: 50
- colors: [lawngreen black]
- error: 'popup
- ip: none
Note: all this options apply only for the current RSP script.
Example
HTTP request: GET /test.rsp
test.rsp : <%
debug/options [
colors: [black white] ;-- invert color contrast
lines: 300 ;-- display more trace log lines
]
%>