【问题标题】:Alter response.body in Rack Middleware更改机架中间件中的 response.body
【发布时间】:2015-06-16 09:01:51
【问题描述】:

我正在尝试为 Rails 4.2 应用程序编写一些机架中间件,该应用程序使用 gsub 方法更改响应正文。我发现使用这样的模式的旧示例:

class MyMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    # do some stuff
    [status, headers, response]
  end
end

我发现response.body 没有设置方法。我可以从其他模式开始修改身体吗?

【问题讨论】:

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


    【解决方案1】:

    问题在于它需要一个数组作为call 方法中的第三个参数。这种模式让我重新开始工作。

    # not real code, just a pattern to follow
    class MyMiddleware
      def initialize(app)
        @app = app
      end
    
      def call(env)
        status, headers, response = @app.call(env)
        new_response = make_new_response(response.body)
        # also must reset the Content-Length header if changing body
        headers['Content-Length'] = new_response.bytesize.to_s
        [status, headers, [new_response]]
      end
    end
    

    【讨论】:

    • 什么是make_new_response
    • @AjaxLeung 任何你想要的。只是一个例子。接受一个字符串,返回一个字符串。
    • 如果你首先使用status, headers, response = @app.call(env),那么之后的一切都无法“停止”请求。您为中间件跳过中间件堆栈。
    • 我已将代码从 new_response.length 更新为 new_response.bytesize。按照 Content-Length 的指示,前面的代码会使浏览器截断一些响应。
    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2011-01-16
    • 2023-03-22
    • 2011-01-14
    相关资源
    最近更新 更多