Rails 3 middleware modify request headers
Asked Answered
B

1

18

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"
Bobbery answered 5/8, 2011 at 16:49 Comment(0)
C
22

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

Chryselephantine answered 5/8, 2011 at 17:0 Comment(5)
Great, I'll give this a try, do you know if my setup intercepts the headers before Rack does or does the order of loading middleware matter at all in terms of execution order.Bobbery
I believe Rack will still intercept the request first, but then pass it on to the middleware instead of directly to Rails. But I'm not 100% sure.Chryselephantine
If that's the case, then it won't work for me. I just dumped the @app object class and it shows Rack::Lock meaning that Rack has already gotten to it. Argh.Bobbery
I was looking at the source of Rack and I can't find any reference in which the headers are prefixed with 'HTTP_'. I must be looking in the wrong place, where can I find it?Musk
Note that if you're trying to access a header with hyphens (-), the hyphens become underscores (_) as well. For example, a header called X-Token is accessed as follows: env['HTTP_X_TOKEN'].Hanger

© 2022 - 2024 — McMap. All rights reserved.