5

It looks like there are multiple ways of fetching headers using Rails. If the request has a header named X-Header, all of the three work:

  1. request.headers["HTTP_X_HEADER"]
  2. request.headers["X_HEADER"]
  3. request.headers["X-Header"]

Which one should I use? Is there a convention over this?

vinibrsl
  • 6,563
  • 4
  • 31
  • 44

1 Answers1

4

If you take a look at implementation of Rails request header, you can see that the header name is "sanitized" first, passing it to the Rack::Request::Env object – https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/headers.rb#L122

    # Converts an HTTP header name to an environment variable name if it is
    # not contained within the headers hash.
    def env_name(key)
      key = key.to_s
      if HTTP_HEADER.match?(key)
        key = key.upcase.tr("-", "_")
        key = "HTTP_" + key unless CGI_VARIABLES.include?(key)
      end
      key
    end

Rails will upcase the header name for you, as well as convert - to _ and prepend the HTTP_ if needed.

Taking this in consideration:

request.headers["HTTP_X_APPENGINE_COUNTRY"] – I'd avoid this one, as Rails will prepend HTTP_.

request.headers["X_APPENGINE_COUNTRY"] – I see nothing wrong with useing this one.

request.headers["X-AppEngine-Country"] – This is the one I'd choose, since the header name is in its original format.

Cheers!

Mladen Ilić
  • 1,667
  • 1
  • 17
  • 21