Class: Rack::Brotli::Deflater
- Inherits:
-
Object
- Object
- Rack::Brotli::Deflater
- Defined in:
- lib/rack/brotli/deflater.rb
Overview
This middleware enables compression of http responses.
Currently supported compression algorithms:
* br
The middleware automatically detects when compression is supported and allowed. For example no transformation is made when a cache directive of ‘no-transform’ is present, or when the response status code is one that doesn’t allow an entity body.
Defined Under Namespace
Classes: BrotliStream
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ Deflater
constructor
Creates Rack::Brotli middleware.
Constructor Details
#initialize(app, options = {}) ⇒ Deflater
Creates Rack::Brotli middleware.
- app
-
rack app instance
- options
-
hash of deflater options, i.e. ‘if’ - a lambda enabling / disabling deflation based on returned boolean value
e.g use Rack::Brotli, :if => lambda { |env, status, headers, body| body.map(&:bytesize).reduce(0, :+) > 512 }‘include’ - a list of content types that should be compressed ‘deflater’ - Brotli compression options
25 26 27 28 29 30 31 |
# File 'lib/rack/brotli/deflater.rb', line 25 def initialize(app, = {}) @app = app @condition = [:if] @compressible_types = [:include] @deflater_options = { quality: 5 }.merge([:deflater] || {}) end |
Instance Method Details
#call(env) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/rack/brotli/deflater.rb', line 33 def call(env) status, headers, body = @app.call(env) headers = Rack::Utils::HeaderHash.new(headers) unless should_deflate?(env, status, headers, body) return [status, headers, body] end request = Rack::Request.new(env) encoding = Rack::Utils.select_best_encoding(%w(br), request.accept_encoding) return [status, headers, body] unless encoding # Set the Vary HTTP header. vary = headers["Vary"].to_s.split(",").map(&:strip) unless vary.include?("*") || vary.include?("Accept-Encoding") headers["Vary"] = vary.push("Accept-Encoding").join(",") end case encoding when "br" headers['Content-Encoding'] = "br" headers.delete(Rack::CONTENT_LENGTH) [status, headers, BrotliStream.new(body, @deflater_options)] when nil = "An acceptable encoding for the requested resource #{request.fullpath} could not be found." bp = Rack::BodyProxy.new([]) { body.close if body.respond_to?(:close) } [406, {Rack::CONTENT_TYPE => "text/plain", Rack::CONTENT_LENGTH => .length.to_s}, bp] end end |