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"
Bob
  • 8,424
  • 17
  • 72
  • 110

1 Answers1

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

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • 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. – Bob Aug 05 '11 at 17:04
  • 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. – Dylan Markow Aug 05 '11 at 17:11
  • 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. – Bob Aug 05 '11 at 17:28
  • 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? – harm Jan 20 '12 at 11:09
  • 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']`. – HartleySan Mar 22 '21 at 13:40