【问题标题】:How to accept gzipped requests in a rails 5 application?如何在 rails 5 应用程序中接受 gzipped 请求?
【发布时间】:2017-03-07 19:38:04
【问题描述】:

过去我使用过this solution,但是自从Rails 5 deprecated ParamsParser 中间件之后,它就不再起作用了。

【问题讨论】:

  • ActionDispatch::Cookies之前插入是否有效?哪个是它之后的中间件,并且仍然存在。
  • 你可以使用nginx解压nginx.com/resources/admin-guide/compression-and-decompression来实现解决方案,这样rails就不用处理了,得到正确的内容。
  • 非常感谢您的赏金。很高兴它对您有所帮助!

标签: ruby-on-rails rack ruby-on-rails-5


【解决方案1】:

如果您在 Rack::Head 之前插入中间件,这应该可以工作

config.middleware.insert_before Rack::Head, "CompressedRequests"

这应该可以解决问题

您可以使用以下命令检查应用的中间件堆栈

rake middleware

【讨论】:

  • 你的回复和@itsnikolay几乎一样,我只接受了他的而不是你的,因为他做了更多的解释和测试。不过还是谢谢:)
  • 我先加了!哈哈,但没关系,只要它解决了你的问题:)
【解决方案2】:

只需添加:

# config/initializers/middlewares.rb
require 'compressed_requests'

Rails.application.configure do
  config.middleware.insert_after Rack::Sendfile, CompressedRequests
end


# lib/compressed_requests.rb
# Copy the file from the article

您可以使用以下方法对其进行测试:

# config/routes.rb
post '/', to: 'welcome#create'

# app/controllers/welcome_controller.rb
class WelcomeController < ActionController::Base
  def create
    render json: params
  end
end

然后做请求:

curl --data-binary @<(echo "Uncompressed data" | gzip) \
     -H "CONTENT_ENCODING: gzip" \
     localhost:3000

{"Uncompressed data\n":null,"controller":"welcome","action":"create"}%

【讨论】:

    【解决方案3】:

    在您的 routes.rb 文件中:

    post 'my_endpoint', to: 'api#my_endpoint'
    

    在您的 api_controller.rb 上:

    class ApiController < ActionController::Base
      def my_endpoint
        render json: JSON.parse(ActiveSupport::Gzip.decompress(request.body.string))
      end
    end
    

    我已经使用 Paw 客户端在全新的 Rails 5 应用程序上对此进行了测试:

    【讨论】:

    • is 并不是一个很好的解决方案,因为它是特定于每个操作的,并且您每次都需要手动进行减压。
    • @DiegoPlentz 如果你想重用它,你可以有一个 decompressed_body 方法来保存重要的位(JSON.parse(ActiveSupport::Gzip.decompress(request.body.string)))。该方法可以存在于您的 API 基本控制器中,或者存在于控制器关注点中,使您能够重用它并保持代码 DRY。
    【解决方案4】:

    【讨论】:

    • 这不起作用。它只解压缩响应,而不是请求。
    猜你喜欢
    • 2018-02-28
    • 2019-02-01
    • 1970-01-01
    • 2023-03-19
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多