rack.git  about / heads / tags
a modular Ruby webserver interface
blob cbac93abcf37ec442babf308794206d2ff1524e7 806 bytes (raw)
$ git show chunk:lib/rack/content_length.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
# frozen_string_literal: true

require_relative 'constants'
require_relative 'utils'

module Rack

  # Sets the content-length header on responses that do not specify
  # a content-length or transfer-encoding header.  Note that this
  # does not fix responses that have an invalid content-length
  # header specified.
  class ContentLength
    include Rack::Utils

    def initialize(app)
      @app = app
    end

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

      if !STATUS_WITH_NO_ENTITY_BODY.key?(status.to_i) &&
         !headers[CONTENT_LENGTH] &&
         !headers[TRANSFER_ENCODING] &&
         body.respond_to?(:to_ary)

        response[2] = body = body.to_ary
        headers[CONTENT_LENGTH] = body.sum(&:bytesize).to_s
      end

      response
    end
  end
end

git clone https://yhbt.net/rack.git