Alter response.body in Rack Middleware

心已入冬 提交于 2019-12-22 08:16:02

问题


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

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?


回答1:


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.length.to_s
    [status, headers, [new_response]]
  end
end


来源:https://stackoverflow.com/questions/29564883/alter-response-body-in-rack-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!