Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added ability to pass options to Rack::Deflater.

* min_content_length option is made against 'Content-Length' header to determine if request should be compressed.
  • Loading branch information...
commit 31804ee1da4bea07566546068e231ad5bed730e3 1 parent 1824547
@jakubpawlowicz authored
Showing with 36 additions and 4 deletions.
  1. +7 −1 lib/rack/deflater.rb
  2. +29 −3 test/spec_deflater.rb
View
8 lib/rack/deflater.rb
@@ -5,8 +5,9 @@
module Rack
class Deflater
- def initialize(app)
+ def initialize(app, options = {})
@app = app
+ @options = options
end
def call(env)
@@ -21,6 +22,11 @@ def call(env)
return [status, headers, body]
end
+ # Skip if request body is too short
+ if headers['Content-Length'] && headers['Content-Length'].to_i < @options[:min_content_length]
+ return [status, headers, body]
+ end
+
request = Request.new(env)
encoding = Utils.select_best_encoding(%w(gzip deflate identity),
View
32 test/spec_deflater.rb
@@ -9,10 +9,10 @@
describe Rack::Deflater do
::Enumerator = ::Enumerable::Enumerator unless Object.const_defined?(:Enumerator)
- def deflater(app)
- Rack::Lint.new Rack::Deflater.new(app)
+ def deflater(app, options = {})
+ Rack::Lint.new Rack::Deflater.new(app, options)
end
-
+
def build_response(status, body, accept_encoding, headers = {})
body = [body] if body.respond_to? :to_str
app = lambda do |env|
@@ -204,4 +204,30 @@ class << body; def each; yield("foo"); yield("bar"); end; end
response[2].each { |part| buf << part }
inflate(buf).should.equal("Hello World!")
end
+
+ should "do nothing if body length is less than a given threshold" do
+ body = 'Hello World!'
+ app = lambda do |env|
+ [200, {'Content-Type' => 'text/plain', 'Content-Encoding' => 'identity', 'Content-Length' => body.length.to_s }, [body]]
+ end
+ request = Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => "gzip")
+ response = deflater(app, { min_content_length: body.length + 1 }).call(request)
+
+ response[0].should.equal(200)
+ Enumerator.new(response[2]).to_a.join.should.equal("Hello World!")
+ end
+
+ should "gzip response if body length is equal or longer than a given threshold" do
+ body = 'Hello World!'
+ app = lambda do |env|
+ [200, {'Content-Type' => 'text/plain', 'Content-Encoding' => 'identity', 'Content-Length' => body.length.to_s }, [body]]
+ end
+ request = Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => "gzip")
+ response = deflater(app, { min_content_length: body.length }).call(request)
+
+ response[0].should.equal(200)
+ gz = Zlib::GzipReader.new(StringIO.new(Enumerator.new(response[2]).to_a.join('')))
+ gz.read.should.equal(body)
+ gz.close
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.