Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rack::Request - how do I get all headers?

The title is pretty self-explanatory. Is there any way to get the headers (except for Rack::Request.env[])?

like image 254
PJK Avatar asked Jun 11 '11 18:06

PJK


People also ask

DOES GET request have header?

This request header is used with GET method to make it conditional: if the requested document has not changed since the time specified in this field the document will not be sent, but instead a Not Modified 304 reply. Format of this field is the same as for Date: .

What are the headers in a request?

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.


2 Answers

The HTTP headers are available in the Rack environment passed to your app:

HTTP_ Variables: Variables corresponding to the client-supplied HTTP request headers (i.e., variables whose names begin with HTTP_). The presence or absence of these variables should correspond with the presence or absence of the appropriate HTTP header in the request.

So the HTTP headers are prefixed with "HTTP_" and added to the hash.

Here's a little program that extracts and displays them:

require 'rack'  app = Proc.new do |env|   headers = env.select {|k,v| k.start_with? 'HTTP_'}     .collect {|key, val| [key.sub(/^HTTP_/, ''), val]}     .collect {|key, val| "#{key}: #{val}<br>"}     .sort   [200, {'Content-Type' => 'text/html'}, headers] end  Rack::Server.start :app => app, :Port => 8080 

When I run this, in addition to the HTTP headers as shown by Chrome or Firefox, there is a "VERSION: HTPP/1.1" (i.e. an entry with key "HTTP_VERSION" and value "HTTP/1.1" is being added to the env hash).

like image 172
matt Avatar answered Sep 25 '22 23:09

matt


Based on @matt's answer, but this really gives you the request headers in a hash as requested in the question:

headers = Hash[*env.select {|k,v| k.start_with? 'HTTP_'}   .collect {|k,v| [k.sub(/^HTTP_/, ''), v]}   .collect {|k,v| [k.split('_').collect(&:capitalize).join('-'), v]}   .sort   .flatten] 

Depending on what key convention you prefer you might want to use something else instead of :capitalize.

like image 29
Gavriel Avatar answered Sep 26 '22 23:09

Gavriel