summaryrefslogtreecommitdiff
path: root/app/middleware/content_length.rb
blob: fa5116067a95ee276a4a79dd6ce7ed7f7c86878a (plain)
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
require 'rack/utils'

class ContentLength

  include Rack::Utils

  def initialize app
    @app = app
  end
  
  def call env
    status, headers, body = @app.call(env)
    headers = HeaderHash.new(headers)
    if !STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) &&
       !headers['Content-Length'] &&
       !headers['Transfer-Encoding']

       #see https://stackoverflow.com/questions/26534165/unable-to-get-content-length-header-working-under-rails-4-1puma
       #see https://github.com/rails/rails/pull/16793
       #&& body.respond_to?(:to_ary)

      obody = body
      body, length = [], 0
      obody.each { |part| body << part; length += bytesize(part) }
      obody.close if obody.respond_to?(:close)

      headers['Content-Length'] = length.to_s
    end
    [status, headers, body]
  end

end