Rails 3 middleware modify request headers

廉价感情. 提交于 2019-12-06 17:39:43

问题


My setup: Rails 3.0.9, Ruby 1.9.2

I am working on my first middleware app and it seems like all of the examples deal with modify the response. I need to examine and modify the request headers in particular, delete some offending headers that cause a bug in Rack 1.2.3 to choke. Here's the typical hello world Rack app.

my_middleware.rb

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

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

Does anyone have an example that deals with the request headrers and intercepting them before Rack gets hold of it? I need to modify the request headers before it gets to Rack for parsing. I have this setup, thinking that putting it before Rack might do the trick but I am not sure if order of execution is enforced in this manner.

application.rb

config.middleware.insert_before Rack::Lock, "MyMiddleware"

回答1:


In your call method, you should be able to modify env, which is the Rack Environment. Rack prepends HTTP_ to each header, so the Accept header would be accessed via env['HTTP_ACCEPT'].

So if you need to delete certain headers, you should be able to do something like env.delete('HTTP_ACCEPT'). Then when you do @app.call(env), it will use your modified env.

See the Rack documentation for more information on the env object (see "The Environment").



来源:https://stackoverflow.com/questions/6959798/rails-3-middleware-modify-request-headers

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