更改 Rack Middleware 中的 response.body

2024-04-11

我正在尝试为 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。我可以从另一种模式开始来改变身体吗?


问题是它需要一个数组作为第三个参数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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改 Rack Middleware 中的 response.body 的相关文章

随机推荐