From 60d878d0a0bfd7ba89aae8fc7cf4dac6400fb58e Mon Sep 17 00:00:00 2001 From: Heiko Bernloehr Date: Thu, 18 Jan 2018 07:30:51 +0100 Subject: Content-Length header via Rails middleware. The Content-Length rack module provided through ruby 2.1 doesn't work correctly with Rails 4.1. So we provide our own. --- app/middleware/content_length.rb | 32 ++++++++++++++++++++++++++++++++ config/application.rb | 3 +++ 2 files changed, 35 insertions(+) create mode 100644 app/middleware/content_length.rb diff --git a/app/middleware/content_length.rb b/app/middleware/content_length.rb new file mode 100644 index 0000000..fa51160 --- /dev/null +++ b/app/middleware/content_length.rb @@ -0,0 +1,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 diff --git a/config/application.rb b/config/application.rb index 3f5e7e0..a41c7f7 100644 --- a/config/application.rb +++ b/config/application.rb @@ -1,11 +1,13 @@ require File.expand_path('../boot', __FILE__) require 'rails/all' +#require 'rack_content_length' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) + module Ecs4 class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. @@ -19,5 +21,6 @@ module Ecs4 # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de + config.middleware.use "ContentLength" end end -- cgit v1.2.3