如何正确使用Ruby CGI模块进行gzip压缩输出?

时间:2015-05-30 20:28:05

标签: ruby encoding cgi gzip deflate

此代码在Firefox 38.0.1(内容编码错误)和Google Chrome 42.0.2311.152(ERR_CONTENT_DECODING_FAILED)中不起作用,但它适用于Opera 12.16和cURL(带 - 压缩选项):

#!/usr/bin/ruby
require "cgi"
require "zlib"

cgi=CGI.new(:accept_charset => "UTF-8")

#header
puts "Content-Type: text/html; charset=\"UTF-8\"" 
puts "Content-Encoding: gzip"
puts

#generating some html output

output=""
output << "<html><body><style> p {line-height:20%;font-size:9px;font-family:monospace} a {text-decoration:none} a[title]:hover:after {font-size:9px;font-family:monospace}</style>"
output << "<p style='text-align:center'>#{Time.now}</p>"
output << "<p>#{"-"*190}</p>"
output<<"</body></html>"

z = Zlib::Deflate.new(9)
compressed = z.deflate(output,Zlib::FINISH)
z.close
puts compressed

此代码适用于所有浏览器,也适用于cURL:

#!/usr/bin/ruby
require "cgi"
require "zlib"

cgi=CGI.new(:accept_charset => "UTF-8")

puts "Content-Type: text/html; charset=\"UTF-8\"" 
puts "Content-Encoding: gzip"
puts

output=""
output << "<html><body><style> p {line-height:20%;font-size:9px;font-family:monospace} a {text-decoration:none} a[title]:hover:after {font-size:9px;font-family:monospace}</style>"
output << "<p style='text-align:center'>#{Time.now}</p>"
output << "<p>#{"-"*190}</p>"
output<<"</body></html>"

File.write("gzip.temp",output)
compressed=IO.popen("cat gzip.temp|gzip -c","r").read
puts compressed

1 个答案:

答案 0 :(得分:0)

好的,问题解决了,必须使用此代码部分:

z = Zlib::Deflate.new(9,16+Zlib::MAX_WBITS)
compressed = z.deflate(output,Zlib::FINISH)
z.close
puts compressed