Action Dispatch HTTP 头
提供对环境中请求的 HTTP 头的访问。
env = { "CONTENT_TYPE" => "text/plain", "HTTP_USER_AGENT" => "curl/7.43.0" }
headers = ActionDispatch::Http::Headers.from_hash(env)
headers["Content-Type"] # => "text/plain"
headers["User-Agent"] # => "curl/7.43.0"
另请注意,当 Rack 服务器将头映射到类似 CGI 的变量时,破折号和下划线都将转换为下划线。此时无法再解决此歧义。必须将下划线和破折号解释为最初以破折号发送的。
# GET / HTTP/1.1
# ...
# User-Agent: curl/7.43.0
# X_Custom_Header: token
headers["X_Custom_Header"] # => nil
headers["X-Custom-Header"] # => "token"
常量
CGI_VARIABLES | = | Set.new(%W[ AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE GATEWAY_INTERFACE HTTPS PATH_INFO PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PORT SERVER_PROTOCOL SERVER_SOFTWARE ]).freeze |
HTTP_HEADER | = | /\A[A-Za-z0-9-]+\z/ |
类公共方法
from_hash(hash) 链接
源代码: 显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 52 def self.from_hash(hash) new ActionDispatch::Request.new hash end
实例公共方法
[](key) 链接
返回映射到 @env 的给定键的值。
源代码: 显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 61 def [](key) @req.get_header env_name(key) end
[]=(key, value) 链接
设置映射到 @env 的键的给定值。
源代码: 显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 66 def []=(key, value) @req.set_header env_name(key), value end
add(key, value) 链接
向多值标头(如 Vary
或 Accept-Encoding
)添加值。
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 71 def add(key, value) @req.add_header env_name(key), value end
each(&block) 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 97 def each(&block) @req.each_header(&block) end
env() 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 118 def env; @req.env.dup; end
fetch(key, default = DEFAULT) 链接
返回映射到 @env 的给定键的值。
如果未找到键且未提供可选代码块,则引发 KeyError
异常。
如果提供了代码块,则会运行该代码块并返回其结果。
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 89 def fetch(key, default = DEFAULT) @req.fetch_header(env_name(key)) do return default unless default == DEFAULT return yield if block_given? raise KeyError, key end end
key?(key) 链接
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 75 def key?(key) @req.has_header? env_name(key) end
merge(headers_or_env) 链接
返回一个新的 Http::Headers
实例,其中包含 headers_or_env
和原始实例的内容。
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 103 def merge(headers_or_env) headers = @req.dup.headers headers.merge!(headers_or_env) headers end
merge!(headers_or_env) 链接
将 headers_or_env
的内容添加到原始实例条目;重复键会被 headers_or_env
中的值覆盖。
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/http/headers.rb, line 112 def merge!(headers_or_env) headers_or_env.each do |key, value| @req.set_header env_name(key), value end end