16 - setting cookies and other http response headers.rb

来自「O Reilly Ruby Cookbook source code」· RB 代码 · 共 41 行

RB
41
字号
#!/usr/bin/ruby# headers.cgirequire "cgi"cgi = CGI.new("html3")# Retrieve or create the "rubycookbook" cookiecookie = cgi.cookies['rubycookbook']cookie = CGI::Cookie.new('rubycookbook', 'hits=0',                          "last=#{Time.now}") if cookie.empty?# Read the values in the cookie for future usehits = cookie.value[0].split('=')[1]last = cookie.value[1].split('=')[1]# Set new values in the cookiecookie.value[0] = "hits=#{hits.succ}"cookie.value[1] = "last=#{Time.now}"#---# Create a hash of HTTP response headers.header = { 'status'      => 'OK',           'cookie'      => [cookie],           'Refresh'     => 2,           'Recipe Name' => 'Setting HTTP Response Headers',           'server'      => ENV['SERVER_SOFTWARE']  }cgi.out(header) do  cgi.html('PRETTY' => '  ') do    cgi.head { cgi.title { 'Setting HTTP Response Headers' } } +    cgi.body do      cgi.p('Your headers:') +      cgi.pre{ cgi.header(header) } +      cgi.pre do        "Number of times your browser hit this cgi: #{hits}\n"+        "Last connected: #{last}"      end    end endend#---

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?