在机架中间件中更改 response.body [英] Alter response.body in Rack Middleware

查看:37
本文介绍了在机架中间件中更改 response.body的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write some Rack Middleware for a Rails 4.2 app that alters the response body using the gsub method. I found older examples that use a pattern like this:

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 没有setter 方法.我可以从另一种模式开始修改正文吗?

What I'm finding is that there is no setter method for response.body. Is there another pattern I can start with to go about modifying the body?

推荐答案

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

The problem was that it expects an Array for the 3rd argument in the call method. This pattern got me working again.

# 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

这篇关于在机架中间件中更改 response.body的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆