Vin*_*sil 5 ruby-on-rails http-headers
看起来有多种使用 Rails 获取标头的方法。如果请求有一个名为 的标头X-Header,则所有三个都有效:
request.headers["HTTP_X_HEADER"]request.headers["X_HEADER"]request.headers["X-Header"]我应该使用哪一个?这方面有约定吗?
如果您查看 Rails 请求标头的实现,您可以看到标头名称首先被“清理”,将其传递给对象Rack::Request::Env\xe2\x80\x93 https://github.com/rails/rails/blob/主/actionpack/lib/action_dispatch/http/headers.rb#L122
# Converts an HTTP header name to an environment variable name if it is\n # not contained within the headers hash.\n def env_name(key)\n key = key.to_s\n if HTTP_HEADER.match?(key)\n key = key.upcase.tr("-", "_")\n key = "HTTP_" + key unless CGI_VARIABLES.include?(key)\n end\n key\n end\nRun Code Online (Sandbox Code Playgroud)\n\nRails 将为upcase您提供标头名称,并根据需要转换-为_并在前面添加。HTTP_
考虑到这一点:
\n\nrequest.headers["HTTP_X_APPENGINE_COUNTRY"]\xe2\x80\x93 我会避免这个,因为 Rails 会在前面添加HTTP_.
request.headers["X_APPENGINE_COUNTRY"]\xe2\x80\x93 我认为使用这个没有什么问题。
request.headers["X-AppEngine-Country"]\xe2\x80\x93 这是我选择的,因为标头名称采用其原始格式。
干杯!
\n| 归档时间: |
|
| 查看次数: |
1464 次 |
| 最近记录: |