8
votes

I'm trying to get request headers in their original format from Rack using Ruby, but haven't been able to figure it out yet. The hash I get back from request.env isn't what I want. In that hash, the header keys are upcased and have underscores instead of dashes, like so:

"CONTENT_TYPE"=>"application/json; charset=utf-8"

What I want is the headers before they get processed, I'm looking for:

"Content_Type"=>"application/json; charset=utf-8"

I can easily enough loop through request.env looking for headers that start with HTTP_ and split them, capitalize each word and gsub to replace underscores with dashes to get them into the format I want. It becomes trickier to retain original format this way when dealing with headers such as:

"X-BT-RequestId"

I feel that I ought to be able to get at the pre-processed headers somehow.

I'm writing a HTTP listener that will wrap a request and forward it on to another service and I want to preserve headers in their original format. I know headers are supposed to be case insensitive, but if I can forward them in their original format, I can hopefully prevent case-sensitive issues later on when my database users are querying for values based on these headers.

Any ideas?

1
Could you write a Rack middleware to solve this problem? That'd be the easiest way to use the request data before any pre-processing. - etagwerker

1 Answers

2
votes

You can get the raw headers in webrick/httpserver.rb from the raw_header instance variable of WEBrick::HTTPRequest:

p req.instance_variable_get("@raw_header")
si.service(req, res)

You can also get it from inside the service method in handler/webrick.rb.