| Class | CGI |
| In: |
lib/cgi/session.rb
lib/cgi.rb lib/cgi-lib.rb |
| Parent: | Object |
CGI class. See documentation for the file cgi.rb for an overview of the CGI protocol.
CGI is a large class, providing several categories of methods, many of which are mixed in from other modules. Some of the documentation is in this class, some in the modules CGI::QueryExtension and CGI::HtmlExtension. See CGI::Cookie for specific information on handling cookies, and cgi/session.rb (CGI::Session) for information on sessions.
For queries, CGI provides methods to get at environmental variables, parameters, cookies, and multipart request data. For responses, CGI provides methods for writing output and generating HTML.
Read on for more details. Examples are provided at the bottom.
The CGI class dynamically mixes in parameter and cookie-parsing functionality, environmental variable access, and support for parsing multipart requests (including uploaded files) from the CGI::QueryExtension module.
The standard CGI environmental variables are available as read-only attributes of a CGI object. The following is a list of these variables:
AUTH_TYPE HTTP_HOST REMOTE_IDENT CONTENT_LENGTH HTTP_NEGOTIATE REMOTE_USER CONTENT_TYPE HTTP_PRAGMA REQUEST_METHOD GATEWAY_INTERFACE HTTP_REFERER SCRIPT_NAME HTTP_ACCEPT HTTP_USER_AGENT SERVER_NAME HTTP_ACCEPT_CHARSET PATH_INFO SERVER_PORT HTTP_ACCEPT_ENCODING PATH_TRANSLATED SERVER_PROTOCOL HTTP_ACCEPT_LANGUAGE QUERY_STRING SERVER_SOFTWARE HTTP_CACHE_CONTROL REMOTE_ADDR HTTP_FROM REMOTE_HOST
For each of these variables, there is a corresponding attribute with the same name, except all lower case and without a preceding HTTP_. content_length and server_port are integers; the rest are strings.
The method params() returns a hash of all parameters in the request as name/value-list pairs, where the value-list is an Array of one or more values. The CGI object itself also behaves as a hash of parameter names to values, but only returns a single value (as a String) for each parameter name.
For instance, suppose the request contains the parameter "favourite_colours" with the multiple values "blue" and "green". The following behaviour would occur:
cgi.params["favourite_colours"] # => ["blue", "green"] cgi["favourite_colours"] # => "blue"
If a parameter does not exist, the former method will return an empty array, the latter an empty string. The simplest way to test for existence of a parameter is by the has_key? method.
HTTP Cookies are automatically parsed from the request. They are available from the cookies() accessor, which returns a hash from cookie name to CGI::Cookie object.
If a request‘s method is POST and its content type is multipart/form-data, then it may contain uploaded files. These are stored by the QueryExtension module in the parameters of the request. The parameter name is the name attribute of the file input field, as usual. However, the value is not a string, but an IO object, either an IOString for small files, or a Tempfile for larger ones. This object also has the additional singleton methods:
| local_path(): | the path of the uploaded file on the local filesystem |
| original_filename(): | the name of the file on the client computer |
| content_type(): | the content type of the file |
The CGI class provides methods for sending header and content output to the HTTP client, and mixes in methods for programmatic HTML generation from CGI::HtmlExtension and CGI::TagMaker modules. The precise version of HTML to use for HTML generation is specified at object creation time.
The simplest way to send output to the HTTP client is using the out() method. This takes the HTTP headers as a hash parameter, and the body content via a block. The headers can be generated as a string using the header() method. The output stream can be written directly to using the print() method.
Each HTML element has a corresponding method for generating that element as a String. The name of this method is the same as that of the element, all lowercase. The attributes of the element are passed in as a hash, and the body as a no-argument block that evaluates to a String. The HTML generation module knows which elements are always empty, and silently drops any passed-in body. It also knows which elements require matching closing tags and which don‘t. However, it does not know what attributes are legal for which elements.
There are also some additional HTML generation methods mixed in from the CGI::HtmlExtension module. These include individual methods for the different types of form inputs, and methods for elements that commonly take particular attributes where the attributes can be directly specified as arguments, rather than via a hash.
require "cgi"
cgi = CGI.new
value = cgi['field_name'] # <== value string for 'field_name'
# if not 'field_name' included, then return "".
fields = cgi.keys # <== array of field names
# returns true if form has 'field_name'
cgi.has_key?('field_name')
cgi.has_key?('field_name')
cgi.include?('field_name')
CAUTION! cgi[‘field_name’] returned an Array with the old cgi.rb(included in ruby 1.6)
require "cgi" cgi = CGI.new params = cgi.params
cgi.params is a hash.
cgi.params['new_field_name'] = ["value"] # add new param
cgi.params['field_name'] = ["new_value"] # change value
cgi.params.delete('field_name') # delete param
cgi.params.clear # delete all params
require "pstore"
db = PStore.new("query.db")
db.transaction do
db["params"] = cgi.params
end
require "pstore"
db = PStore.new("query.db")
db.transaction do
cgi.params = db["params"]
end
require "cgi" cgi = CGI.new value = cgi['field_name'] # <== value string for 'field_name' value.read # <== body of value value.local_path # <== path to local file of value value.original_filename # <== original filename of value value.content_type # <== content_type of value
and value has StringIO or Tempfile class methods.
require "cgi"
cgi = CGI.new
values = cgi.cookies['name'] # <== array of 'name'
# if not 'name' included, then return [].
names = cgi.cookies.keys # <== array of cookie names
and cgi.cookies is a hash.
require "cgi"
cgi = CGI.new
for name, cookie in cgi.cookies
cookie.expires = Time.now + 30
end
cgi.out("cookie" => cgi.cookies) {"string"}
cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
require "cgi"
cgi = CGI.new
cgi.cookies['name'].expires = Time.now + 30
cgi.out("cookie" => cgi.cookies['name']) {"string"}
require "cgi"
cgi = CGI.new("html3") # add HTML generation methods
cgi.out() do
cgi.html() do
cgi.head{ cgi.title{"TITLE"} } +
cgi.body() do
cgi.form() do
cgi.textarea("get_text") +
cgi.br +
cgi.submit
end +
cgi.pre() do
CGI::escapeHTML(
"params: " + cgi.params.inspect + "\n" +
"cookies: " + cgi.cookies.inspect + "\n" +
ENV.collect() do |key, value|
key + " --> " + value + "\n"
end.join("")
)
end
end
end
end
# add HTML generation methods
CGI.new("html3") # html3.2
CGI.new("html4") # html4.01 (Strict)
CGI.new("html4Tr") # html4.01 Transitional
CGI.new("html4Fr") # html4.01 Frameset
| CR | = | "\015" |
| LF | = | "\012" |
| EOL | = | CR + LF |
| RFC822_DAYS | = | %w[ Sun Mon Tue Wed Thu Fri Sat ] |
| RFC822_MONTHS | = | %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ] |
| cookie | [R] | |
| inputs | [R] |
make raw cookie string
# File lib/cgi-lib.rb, line 211
211: def CGI::cookie(options)
212: "Set-Cookie: " + options['name'] + '=' + escape(options['value']) +
213: (options['domain'] ? '; domain=' + options['domain'] : '') +
214: (options['path'] ? '; path=' + options['path'] : '') +
215: (options['expires'] ? '; expires=' + rfc1123_date(options['expires']) : '') +
216: (options['secure'] ? '; secure' : '')
217: end
URL-encode a string.
url_encoded_string = CGI::escape("'Stop!' said Fred")
# => "%27Stop%21%27+said+Fred"
# File lib/cgi.rb, line 341
341: def CGI::escape(string)
342: string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
343: '%' + $1.unpack('H2' * $1.size).join('%').upcase
344: end.tr(' ', '+')
345: end
Escape only the tags of certain HTML elements in string.
Takes an element or elements or array of elements. Each element is specified by the name of the element, without angle brackets. This matches both the start and the end tag of that element. The attribute list of the open tag will also be escaped (for instance, the double-quotes surrounding attribute values).
print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
# "<BR><A HREF="url"></A>"
print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
# "<BR><A HREF="url"></A>"
# File lib/cgi.rb, line 417
417: def CGI::escapeElement(string, *elements)
418: elements = elements[0] if elements[0].kind_of?(Array)
419: unless elements.empty?
420: string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
421: CGI::escapeHTML($&)
422: end
423: else
424: string
425: end
426: end
Escape special characters in HTML, namely &\"<>
CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
# File lib/cgi.rb, line 361
361: def CGI::escapeHTML(string)
362: string.gsub(/&/n, '&').gsub(/\"/n, '"').gsub(/>/n, '>').gsub(/</n, '<')
363: end
make HTTP header string
# File lib/cgi-lib.rb, line 220
220: def CGI::header(*options)
221: if defined?(MOD_RUBY)
222: options.each{|option|
223: option.sub(/(.*?): (.*)/){
224: Apache::request.headers_out[$1] = $2
225: }
226: }
227: Apache::request.send_http_header
228: ''
229: else
230: if options.delete("nph") or (ENV['SERVER_SOFTWARE'] =~ /IIS/)
231: [(ENV['SERVER_PROTOCOL'] or "HTTP/1.0") + " 200 OK",
232: "Date: " + rfc1123_date(Time.now),
233: "Server: " + (ENV['SERVER_SOFTWARE'] or ""),
234: "Connection: close"] +
235: (options.empty? ? ["Content-Type: text/html"] : options)
236: else
237: options.empty? ? ["Content-Type: text/html"] : options
238: end.join(EOL) + EOL + EOL
239: end
240: end
# File lib/cgi-lib.rb, line 248
248: def CGI::message(message, title = "", header = ["Content-Type: text/html"])
249: if message.kind_of?(Hash)
250: title = message['title']
251: header = message['header']
252: message = message['body']
253: end
254: CGI::print(*header){
255: CGI::tag("HTML"){
256: CGI::tag("HEAD"){ CGI.tag("TITLE"){ title } } +
257: CGI::tag("BODY"){ message }
258: }
259: }
260: true
261: end
# File lib/cgi-lib.rb, line 162
162: def initialize(input = $stdin)
163:
164: @inputs = {}
165: @cookie = {}
166:
167: case ENV['REQUEST_METHOD']
168: when "GET"
169: ENV['QUERY_STRING'] or ""
170: when "POST"
171: input.read(Integer(ENV['CONTENT_LENGTH'])) or ""
172: else
173: read_from_cmdline
174: end.split(/[&;]/).each do |x|
175: key, val = x.split(/=/,2).collect{|x|CGI::unescape(x)}
176: if @inputs.include?(key)
177: @inputs[key] += "\0" + (val or "")
178: else
179: @inputs[key] = (val or "")
180: end
181: end
182:
183: super(@inputs)
184:
185: if ENV.has_key?('HTTP_COOKIE') or ENV.has_key?('COOKIE')
186: (ENV['HTTP_COOKIE'] or ENV['COOKIE']).split(/; /).each do |x|
187: key, val = x.split(/=/,2)
188: key = CGI::unescape(key)
189: val = val.split(/&/).collect{|x|CGI::unescape(x)}.join("\0")
190: if @cookie.include?(key)
191: @cookie[key] += "\0" + val
192: else
193: @cookie[key] = val
194: end
195: end
196: end
197: end
type specifies which version of HTML to load the HTML generation methods for. The following versions of HTML are supported:
| html3: | HTML 3.x |
| html4: | HTML 4.0 |
| html4Tr: | HTML 4.0 Transitional |
| html4Fr: | HTML 4.0 with Framesets |
If not specified, no HTML generation methods will be loaded.
If the CGI object is not created in a standard CGI call environment (that is, it can‘t locate REQUEST_METHOD in its environment), then it will run in "offline" mode. In this mode, it reads its parameters from the command line or (failing that) from standard input. Otherwise, cookies and other parameters are parsed automatically from the standard CGI locations, which varies according to the REQUEST_METHOD.
# File lib/cgi.rb, line 2286
2286: def initialize(type = "query")
2287: if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
2288: Apache.request.setup_cgi_env
2289: end
2290:
2291: extend QueryExtension
2292: @multipart = false
2293: if defined?(CGI_PARAMS)
2294: warn "do not use CGI_PARAMS and CGI_COOKIES"
2295: @params = CGI_PARAMS.dup
2296: @cookies = CGI_COOKIES.dup
2297: else
2298: initialize_query() # set @params, @cookies
2299: end
2300: @output_cookies = nil
2301: @output_hidden = nil
2302:
2303: case type
2304: when "html3"
2305: extend Html3
2306: element_init()
2307: extend HtmlExtension
2308: when "html4"
2309: extend Html4
2310: element_init()
2311: extend HtmlExtension
2312: when "html4Tr"
2313: extend Html4Tr
2314: element_init()
2315: extend HtmlExtension
2316: when "html4Fr"
2317: extend Html4Tr
2318: element_init()
2319: extend Html4Fr
2320: element_init()
2321: extend HtmlExtension
2322: end
2323: end
Parse an HTTP query string into a hash of key=>value pairs.
params = CGI::parse("query_string")
# {"name1" => ["value1", "value2", ...],
# "name2" => ["value1", "value2", ...], ... }
# File lib/cgi.rb, line 894
894: def CGI::parse(query)
895: params = Hash.new([].freeze)
896:
897: query.split(/[&;]/n).each do |pairs|
898: key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
899: if params.has_key?(key)
900: params[key].push(value)
901: else
902: params[key] = [value]
903: end
904: end
905:
906: params
907: end
Prettify (indent) an HTML string.
string is the HTML string to indent. shift is the indentation unit to use; it defaults to two spaces.
print CGI::pretty("<HTML><BODY></BODY></HTML>")
# <HTML>
# <BODY>
# </BODY>
# </HTML>
print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
# <HTML>
# <BODY>
# </BODY>
# </HTML>
# File lib/cgi.rb, line 1213
1213: def CGI::pretty(string, shift = " ")
1214: lines = string.gsub(/(?!\A)<(?:.|\n)*?>/n, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
1215: end_pos = 0
1216: while end_pos = lines.index(/^<\/(\w+)/n, end_pos)
1217: element = $1.dup
1218: start_pos = lines.rindex(/^\s*<#{element}/ni, end_pos)
1219: lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/n, "\n" + shift) + "__"
1220: end
1221: lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/n, '\1')
1222: end
Format a Time object as a String using the format specified by RFC 1123.
CGI::rfc1123_date(Time.now)
# Sat, 01 Jan 2000 00:00:00 GMT
# File lib/cgi.rb, line 454
454: def CGI::rfc1123_date(time)
455: t = time.clone.gmtime
456: return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
457: RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
458: t.hour, t.min, t.sec)
459: end
make rfc1123 date string
# File lib/cgi-lib.rb, line 126
126: def CGI::rfc1123_date(time)
127: t = time.clone.gmtime
128: return format("%s, %.2d %s %d %.2d:%.2d:%.2d GMT",
129: RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
130: t.hour, t.min, t.sec)
131: end
make HTML tag string
# File lib/cgi-lib.rb, line 203
203: def CGI::tag(element, attributes = {})
204: "<" + escapeHTML(element) + attributes.collect{|name, value|
205: " " + escapeHTML(name) + '="' + escapeHTML(value) + '"'
206: }.to_s + ">" +
207: (iterator? ? yield.to_s + "</" + escapeHTML(element) + ">" : "")
208: end
URL-decode a string.
string = CGI::unescape("%27Stop%21%27+said+Fred")
# => "'Stop!' said Fred"
# File lib/cgi.rb, line 351
351: def CGI::unescape(string)
352: string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
353: [$1.delete('%')].pack('H*')
354: end
355: end
Undo escaping such as that done by CGI::escapeElement()
print CGI::unescapeElement(
CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
# "<BR><A HREF="url"></A>"
print CGI::unescapeElement(
CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
# "<BR><A HREF="url"></A>"
# File lib/cgi.rb, line 438
438: def CGI::unescapeElement(string, *elements)
439: elements = elements[0] if elements[0].kind_of?(Array)
440: unless elements.empty?
441: string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
442: CGI::unescapeHTML($&)
443: end
444: else
445: string
446: end
447: end
Unescape a string that has been HTML-escaped
CGI::unescapeHTML("Usage: foo "bar" <baz>")
# => "Usage: foo \"bar\" <baz>"
# File lib/cgi.rb, line 369
369: def CGI::unescapeHTML(string)
370: string.gsub(/&(.*?);/n) do
371: match = $1.dup
372: case match
373: when /\Aamp\z/ni then '&'
374: when /\Aquot\z/ni then '"'
375: when /\Agt\z/ni then '>'
376: when /\Alt\z/ni then '<'
377: when /\A#0*(\d+)\z/n then
378: if Integer($1) < 256
379: Integer($1).chr
380: else
381: if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
382: [Integer($1)].pack("U")
383: else
384: "&##{$1};"
385: end
386: end
387: when /\A#x([0-9a-f]+)\z/ni then
388: if $1.hex < 256
389: $1.hex.chr
390: else
391: if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
392: [$1.hex].pack("U")
393: else
394: "&#x#{$1};"
395: end
396: end
397: else
398: "&#{match};"
399: end
400: end
401: end
Create an HTTP header block as a string.
Includes the empty line that ends the header block.
options can be a string specifying the Content-Type (defaults to text/html), or a hash of header key/value pairs. The following header keys are recognized:
| type: | the Content-Type header. Defaults to "text/html" |
| charset: | the charset of the body, appended to the Content-Type header. |
| nph: | a boolean value. If true, prepend protocol string and status code, and date; and sets default values for "server" and "connection" if not explicitly set. |
| status: | the HTTP status code, returned as the Status header. See the list of available status codes below. |
| server: | the server software, returned as the Server header. |
| connection: | the connection type, returned as the Connection header (for instance, "close". |
| length: | the length of the content that will be sent, returned as the Content-Length header. |
| language: | the language of the content, returned as the Content-Language header. |
| expires: | the time on which the current content expires, as a Time object, returned as the Expires header. |
| cookie: | a cookie or cookies, returned as one or more Set-Cookie headers. The value can be the literal string of the cookie; a CGI::Cookie object; an Array of literal cookie strings or Cookie objects; or a hash all of whose values are literal cookie strings or Cookie objects. These cookies are in addition to the cookies held in the @output_cookies field. |
Other header lines can also be set; they are appended as key: value.
header
# Content-Type: text/html
header("text/plain")
# Content-Type: text/plain
header("nph" => true,
"status" => "OK", # == "200 OK"
# "status" => "200 GOOD",
"server" => ENV['SERVER_SOFTWARE'],
"connection" => "close",
"type" => "text/html",
"charset" => "iso-2022-jp",
# Content-Type: text/html; charset=iso-2022-jp
"length" => 103,
"language" => "ja",
"expires" => Time.now + 30,
"cookie" => [cookie1, cookie2],
"my_header1" => "my_value"
"my_header2" => "my_value")
The status codes are:
"OK" --> "200 OK" "PARTIAL_CONTENT" --> "206 Partial Content" "MULTIPLE_CHOICES" --> "300 Multiple Choices" "MOVED" --> "301 Moved Permanently" "REDIRECT" --> "302 Found" "NOT_MODIFIED" --> "304 Not Modified" "BAD_REQUEST" --> "400 Bad Request" "AUTH_REQUIRED" --> "401 Authorization Required" "FORBIDDEN" --> "403 Forbidden" "NOT_FOUND" --> "404 Not Found" "METHOD_NOT_ALLOWED" --> "405 Method Not Allowed" "NOT_ACCEPTABLE" --> "406 Not Acceptable" "LENGTH_REQUIRED" --> "411 Length Required" "PRECONDITION_FAILED" --> "412 Precondition Failed" "SERVER_ERROR" --> "500 Internal Server Error" "NOT_IMPLEMENTED" --> "501 Method Not Implemented" "BAD_GATEWAY" --> "502 Bad Gateway" "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"
This method does not perform charset conversion.
# File lib/cgi.rb, line 539
539: def header(options = "text/html")
540:
541: buf = ""
542:
543: case options
544: when String
545: options = { "type" => options }
546: when Hash
547: options = options.dup
548: end
549:
550: unless options.has_key?("type")
551: options["type"] = "text/html"
552: end
553:
554: if options.has_key?("charset")
555: options["type"] += "; charset=" + options.delete("charset")
556: end
557:
558: options.delete("nph") if defined?(MOD_RUBY)
559: if options.delete("nph") or /IIS/n.match(env_table['SERVER_SOFTWARE'])
560: buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0") + " " +
561: (HTTP_STATUS[options["status"]] or options["status"] or "200 OK") +
562: EOL +
563: "Date: " + CGI::rfc1123_date(Time.now) + EOL
564:
565: unless options.has_key?("server")
566: options["server"] = (env_table['SERVER_SOFTWARE'] or "")
567: end
568:
569: unless options.has_key?("connection")
570: options["connection"] = "close"
571: end
572:
573: options.delete("status")
574: end
575:
576: if options.has_key?("status")
577: buf += "Status: " +
578: (HTTP_STATUS[options["status"]] or options["status"]) + EOL
579: options.delete("status")
580: end
581:
582: if options.has_key?("server")
583: buf += "Server: " + options.delete("server") + EOL
584: end
585:
586: if options.has_key?("connection")
587: buf += "Connection: " + options.delete("connection") + EOL
588: end
589:
590: buf += "Content-Type: " + options.delete("type") + EOL
591:
592: if options.has_key?("length")
593: buf += "Content-Length: " + options.delete("length").to_s + EOL
594: end
595:
596: if options.has_key?("language")
597: buf += "Content-Language: " + options.delete("language") + EOL
598: end
599:
600: if options.has_key?("expires")
601: buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL
602: end
603:
604: if options.has_key?("cookie")
605: if options["cookie"].kind_of?(String) or
606: options["cookie"].kind_of?(Cookie)
607: buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL
608: elsif options["cookie"].kind_of?(Array)
609: options.delete("cookie").each{|cookie|
610: buf += "Set-Cookie: " + cookie.to_s + EOL
611: }
612: elsif options["cookie"].kind_of?(Hash)
613: options.delete("cookie").each_value{|cookie|
614: buf += "Set-Cookie: " + cookie.to_s + EOL
615: }
616: end
617: end
618: if @output_cookies
619: for cookie in @output_cookies
620: buf += "Set-Cookie: " + cookie.to_s + EOL
621: end
622: end
623:
624: options.each{|key, value|
625: buf += key + ": " + value.to_s + EOL
626: }
627:
628: if defined?(MOD_RUBY)
629: table = Apache::request.headers_out
630: buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value|
631: warn sprintf("name:%s value:%s\n", name, value) if $DEBUG
632: case name
633: when 'Set-Cookie'
634: table.add(name, value)
635: when /^status$/ni
636: Apache::request.status_line = value
637: Apache::request.status = value.to_i
638: when /^content-type$/ni
639: Apache::request.content_type = value
640: when /^content-encoding$/ni
641: Apache::request.content_encoding = value
642: when /^location$/ni
643: if Apache::request.status == 200
644: Apache::request.status = 302
645: end
646: Apache::request.headers_out[name] = value
647: else
648: Apache::request.headers_out[name] = value
649: end
650: }
651: Apache::request.send_http_header
652: ''
653: else
654: buf + EOL
655: end
656:
657: end
Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
The header is provided by options, as for header(). The body of the document is that returned by the passed- in block. This block takes no arguments. It is required.
cgi = CGI.new
cgi.out{ "string" }
# Content-Type: text/html
# Content-Length: 6
#
# string
cgi.out("text/plain") { "string" }
# Content-Type: text/plain
# Content-Length: 6
#
# string
cgi.out("nph" => true,
"status" => "OK", # == "200 OK"
"server" => ENV['SERVER_SOFTWARE'],
"connection" => "close",
"type" => "text/html",
"charset" => "iso-2022-jp",
# Content-Type: text/html; charset=iso-2022-jp
"language" => "ja",
"expires" => Time.now + (3600 * 24 * 30),
"cookie" => [cookie1, cookie2],
"my_header1" => "my_value",
"my_header2" => "my_value") { "string" }
Content-Length is automatically calculated from the size of the String returned by the content block.
If ENV[‘REQUEST_METHOD’] == "HEAD", then only the header is outputted (the content block is still required, but it is ignored).
If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then the content is converted to this charset, and the language is set to "ja".
# File lib/cgi.rb, line 702
702: def out(options = "text/html") # :yield:
703:
704: options = { "type" => options } if options.kind_of?(String)
705: content = yield
706:
707: if options.has_key?("charset")
708: require "nkf"
709: case options["charset"]
710: when /iso-2022-jp/ni
711: content = NKF::nkf('-j', content)
712: options["language"] = "ja" unless options.has_key?("language")
713: when /euc-jp/ni
714: content = NKF::nkf('-e', content)
715: options["language"] = "ja" unless options.has_key?("language")
716: when /shift_jis/ni
717: content = NKF::nkf('-s', content)
718: options["language"] = "ja" unless options.has_key?("language")
719: end
720: end
721:
722: options["length"] = content.length.to_s
723: output = stdoutput
724: output.binmode if defined? output.binmode
725: output.print header(options)
726: output.print content unless "HEAD" == env_table['REQUEST_METHOD']
727: end
Print an argument or list of arguments to the default output stream
cgi = CGI.new cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
# File lib/cgi.rb, line 734
734: def print(*options)
735: stdoutput.print(*options)
736: end
offline mode. read name=value pairs on standard input.
# File lib/cgi-lib.rb, line 149
149: def read_from_cmdline
150: require "shellwords.rb"
151: words = Shellwords.shellwords(
152: if not ARGV.empty?
153: ARGV.join(' ')
154: else
155: STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty?
156: readlines.join(' ').gsub(/\n/, '')
157: end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26'))
158:
159: if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end
160: end