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 with the ‘br` encoding, when support is detected and allowed.
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 Hash (see brotli.org/encode.html#a4d4 and github.com/miyucy/brotli/blob/ea0e058031177e5cc42e361f7d2702a951048a31/ext/brotli/brotli.c#L119-L180)
- 'mode' - 'quality' - 'lgwin' - 'lgblock'
25 26 27 28 29 30 31 32 |
# File 'lib/rack/brotli/deflater.rb', line 25 def initialize(app, = {}) @app = app @condition = [:if] @compressible_types = [:include] @deflater_options = { quality: 5 }.merge(.fetch(:deflater, {})) @sync = .fetch(:sync, true) end |
Instance Method Details
#call(env) ⇒ Object
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 65 |
# File 'lib/rack/brotli/deflater.rb', line 34 def call(env) status, headers, body = response = @app.call(env) unless should_deflate?(env, status, headers, body) return response end request = Rack::Request.new(env) encoding = Rack::Utils.select_best_encoding(%w(br identity), request.accept_encoding) # Set the Vary HTTP header. vary = headers["vary"].to_s.split(",").map(&:strip) unless vary.include?("*") || vary.any?{|v| v.downcase == 'accept-encoding'} headers["vary"] = vary.push("Accept-Encoding").join(",") end case encoding when "br" headers['content-encoding'] = "br" headers.delete(Rack::CONTENT_LENGTH) response[2] = BrotliStream.new(body, @sync, @deflater_options) response when "identity" response else # Only possible encoding values here are 'br', 'identity', and 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 |