Rails 3 middleware modify request headers

Bob picture Bob · Aug 5, 2011 · Viewed 9.6k times · Source

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"

Answer

Dylan Markow picture Dylan Markow · Aug 5, 2011

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").