frozen_string_literal: false The HTTPHeader module defines methods for reading and writing HTTP headers.
It is used as a mixin by other classes, to provide hash-like access to HTTP header values. Unlike raw hash access, HTTPHeader provides access via case-insensitive keys. It also provides methods for accessing commonly-used HTTP header values in more convenient formats.
Returns the header field corresponding to the case-insensitive key. For example, a key of “Content-Type” might return “text/html”
# File net/http/header.rb, line 38 def [](key) a = @header[key.downcase.to_s] or return nil a.join(', ') end
Sets the header field corresponding to the case-insensitive key.
# File net/http/header.rb, line 44 def []=(key, val) unless val @header.delete key.downcase.to_s return val end set_field(key, val) end
Adds a value to a named header field, instead of replacing its value.
Second argument val
must be a String. See also []=, [] and get_fields.
request.add_field 'X-My-Header', 'a' p request['X-My-Header'] #=> "a" p request.get_fields('X-My-Header') #=> ["a"] request.add_field 'X-My-Header', 'b' p request['X-My-Header'] #=> "a, b" p request.get_fields('X-My-Header') #=> ["a", "b"] request.add_field 'X-My-Header', 'c' p request['X-My-Header'] #=> "a, b, c" p request.get_fields('X-My-Header') #=> ["a", "b", "c"]
# File net/http/header.rb, line 67 def add_field(key, val) stringified_downcased_key = key.downcase.to_s if @header.key?(stringified_downcased_key) append_field_value(@header[stringified_downcased_key], val) else set_field(key, val) end end
# File net/http/header.rb, line 13 def initialize_http_header(initheader) @header = {} return unless initheader initheader.each do |key, value| warn "net/http: duplicated HTTP header: #{key}", uplevel: 3 if key?(key) and $VERBOSE if value.nil? warn "net/http: nil HTTP header: #{key}", uplevel: 3 if $VERBOSE else value = value.strip # raise error for invalid byte sequences if value.count("\r\n") > 0 raise ArgumentError, "header #{key} has field value #{value.inspect}, this cannot include CR/LF" end @header[key.downcase.to_s] = [value] end end end