當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby CGI.out用法及代碼示例

本文簡要介紹ruby語言中 CGI.out 的用法。

用法

out(content_type_string='text/html')
out(headers_hash)

將 HTTP 標頭和正文打印到 $DEFAULT_OUTPUT ($>)

content_type_string

如果傳遞了一個字符串,則假定它是內容類型。

headers_hash

這是一個 Hash 的標頭,類似於 http_header 使用的標頭。

block

需要一個塊,並且應該評估響應的主體。

Content-Length 是根據內容塊返回的 String 的大小自動計算的。

如果 ENV['REQUEST_METHOD'] == "HEAD" ,則僅輸出標頭(仍需要內容塊,但會被忽略)。

如果字符集是 “iso-2022-jp” 或 “euc-jp” 或 “shift_jis”,則內容將轉換為此字符集,並且語言設置為 “ja”。

例子:

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" }
   # HTTP/1.1 200 OK
   # Date: Sun, 15 May 2011 17:35:54 GMT
   # Server: Apache 2.2.0
   # Connection: close
   # Content-Type: text/html; charset=iso-2022-jp
   # Content-Length: 6
   # Content-Language: ja
   # Expires: Tue, 14 Jun 2011 17:35:54 GMT
   # Set-Cookie: foo
   # Set-Cookie: bar
   # my_header1: my_value
   # my_header2: my_value
   #
   # string

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 CGI.out。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。