Permalink
Browse files

added gzip support to Rack::Deflater

  • Loading branch information...
1 parent a31ee95 commit cabc20df5298271d10af8e84d81d8545642216a2 Ben committed with Jul 4, 2008
Showing with 27 additions and 1 deletion.
  1. +16 −1 lib/rack/deflater.rb
  2. +11 −0 test/spec_rack_deflater.rb
View
@@ -1,4 +1,5 @@
require "zlib"
+require "stringio"
module Rack
@@ -11,9 +12,11 @@ def call(env)
status, headers, body = @app.call(env)
request = Request.new(env)
- encoding = Utils.select_best_encoding(%w(deflate identity), request.accept_encoding)
+ encoding = Utils.select_best_encoding(%w(gzip deflate identity), request.accept_encoding)
case encoding
+ when "gzip"
+ [status, headers.merge("Content-Encoding" => "gzip"), self.class.gzip(body)]
when "deflate"
[status, headers.merge("Content-Encoding" => "deflate"), self.class.deflate(body)]
when "identity"
@@ -24,6 +27,18 @@ def call(env)
end
end
+ def self.gzip(body)
+ io = StringIO.new
+ gzip = Zlib::GzipWriter.new(io)
+
+ # TODO: Add streaming
+ # TODO: Consider all part types
+ body.each { |part| gzip << part }
+
+ gzip.close
+ return io.string
+ end
+
# Loosely based on Mongrel's Deflate handler
def self.deflate(body)
deflater = Zlib::Deflate.new(
View
@@ -32,6 +32,17 @@ class << body; def each; yield("foo"); yield("bar"); end; end
response[1].should.equal({ "Content-Encoding" => "deflate" })
response[2].to_s.should.equal("\363H\315\311\311W(\317/\312IQ\004\000")
end
+
+ specify "should be able to gzip bodies that respond to each" do
+ body = Object.new
+ class << body; def each; yield("foo"); yield("bar"); end; end
+
+ response = build_response(body, "gzip")
+
+ response[0].should.equal(200)
+ response[1].should.equal({ "Content-Encoding" => "gzip" })
+ # response[2].to_s.should.equal("\037\213\b\000J\340mH\000\003K\313\317OJ,\002\000\225\037\366\236\006\000\000\000")
+ end
specify "should be able to fallback to no deflation" do
response = build_response("Hello world!", "superzip")

0 comments on commit cabc20d

Please sign in to comment.