跳到内容 跳到搜索

Action Dispatch HTTP Headers

提供对环境中请求 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"
方法
#
A
E
F
I
K
M
包含的模块

常量

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)

# File actionpack/lib/action_dispatch/http/headers.rb, line 54
def self.from_hash(hash)
  new ActionDispatch::Request.new hash
end

实例公共方法

[](key)

返回映射到 @env 的给定键的值。

# File actionpack/lib/action_dispatch/http/headers.rb, line 63
def [](key)
  @req.get_header env_name(key)
end

[]=(key, value)

设置映射到 @env 的键的给定值。

# File actionpack/lib/action_dispatch/http/headers.rb, line 68
def []=(key, value)
  @req.set_header env_name(key), value
end

add(key, value)

将值添加到多值标头,如 VaryAccept-Encoding

# File actionpack/lib/action_dispatch/http/headers.rb, line 73
def add(key, value)
  @req.add_header env_name(key), value
end

each(&block)

# File actionpack/lib/action_dispatch/http/headers.rb, line 98
def each(&block)
  @req.each_header(&block)
end

env()

# File actionpack/lib/action_dispatch/http/headers.rb, line 118
def env; @req.env.dup; end

fetch(key, default = DEFAULT)

返回映射到 @env 的给定键的值。

如果未找到键并且未提供可选代码块,则会引发 KeyError 异常。

如果提供了代码块,则将运行它并返回其结果。

# File actionpack/lib/action_dispatch/http/headers.rb, line 90
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

include?(key)

别名:key?

key?(key)

别名:include?
# File actionpack/lib/action_dispatch/http/headers.rb, line 77
def key?(key)
  @req.has_header? env_name(key)
end

merge(headers_or_env)

返回一个新的 Http::Headers 实例,其中包含 headers_or_env 和原始实例的内容。

# File actionpack/lib/action_dispatch/http/headers.rb, line 104
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 中的值覆盖。

# 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