Class: Rack::Brotli::Deflater

Inherits:
Deflater
  • Object
show all
Defined in:
lib/rack/brotli/deflater.rb

Overview

This middleware enables content encoding of http responses, usually for purposes of compression.

Currently supported encodings:

  • br

This middleware automatically detects when encoding is supported and allowed. For example no encoding is made when a cache directive of ‘no-transform’ is present, when the response status code is one that doesn’t allow an entity body, or when the body is empty.

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Deflater

Returns a new instance of Deflater.



23
24
25
26
27
# File 'lib/rack/brotli/deflater.rb', line 23

def initialize(app, options = {})
  super

  @deflater_options = { quality: 5 }.merge(options[:deflater] || {})
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
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
# File 'lib/rack/brotli/deflater.rb', line 29

def call(env)
  status, headers, body = response = @app.call(env)

  return response unless should_deflate?(env, status, headers, body)

  request = Request.new(env)

  encoding = 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(CONTENT_LENGTH)
    response[2] = BrotliStream.new(body, @sync, @deflater_options)
    response
  when "identity"
    response
  else # when nil
    # Only possible encoding values here are 'br', 'identity', and nil
    message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found."
    bp = Rack::BodyProxy.new([message]) { body.close if body.respond_to?(:close) }
    [406, { CONTENT_TYPE => "text/plain", CONTENT_LENGTH => message.length.to_s }, bp]
  end
end