Class: PacketGen::Header::HTTP::Headers Abstract

Inherits:
Object
  • Object
show all
Includes:
BinStruct::Structable
Defined in:
lib/packetgen/header/http/headers.rb

Overview

This class is abstract.

Base class for HTTP headers.

Author:

  • Kent ‘picat’ Gruber

Since:

  • 2.2.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHeaders

Returns a new instance of Headers.

Since:

  • 2.2.0



24
25
26
# File 'lib/packetgen/header/http/headers.rb', line 24

def initialize
  @data = {}
end

Instance Attribute Details

#dataHash{String => String}? (readonly) Also known as: to_h

Underlying Headers data.

Returns:

  • (Hash{String => String}, nil)

Since:

  • 2.2.0



21
22
23
# File 'lib/packetgen/header/http/headers.rb', line 21

def data
  @data
end

Instance Method Details

#[](header) ⇒ String

Get header value from its name

Parameters:

  • header (String)

    header name

Returns:

  • (String)

    header value

Since:

  • 2.2.0



49
50
51
# File 'lib/packetgen/header/http/headers.rb', line 49

def [](header)
  data[header]
end

#from_human(data) ⇒ self

Read human-readable data to populate header data.

Parameters:

  • data (Hash{String=>String})

Returns:

  • (self)

Since:

  • 2.2.0



82
83
84
# File 'lib/packetgen/header/http/headers.rb', line 82

def from_human(data)
  read(data)
end

#given?Boolean

Check if any headers were given.

Returns:

  • (Boolean)

Since:

  • 2.2.0



88
89
90
91
92
# File 'lib/packetgen/header/http/headers.rb', line 88

def given?
  return true unless @data.nil? || @data.empty?

  false
end

#header?(header) ⇒ Boolean Also known as: has_header?

Say if self include header header

Parameters:

  • header (String)

    header name

Returns:

  • (Boolean)

Since:

  • 2.2.0



56
57
58
# File 'lib/packetgen/header/http/headers.rb', line 56

def header?(header)
  data.key?(header)
end

#read(s_or_h) ⇒ self

Populate object from a string or directly from a hash.

Parameters:

  • s_or_h (String, Hash{String=>String})

Returns:

  • (self)

Since:

  • 2.2.0



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/packetgen/header/http/headers.rb', line 31

def read(s_or_h)
  case s_or_h
  when String
    @data = s_or_h.split("\n").filter_map do |h|
      next unless h.include?(':')

      k, v = h.split(':', 2)
      [k, v.strip]
    end.to_h
  when Hash
    @data = s_or_h
  end
  self
end

#to_humanHash

Get a human readable hash.

Returns:

  • (Hash)

Since:

  • 2.2.0



75
76
77
# File 'lib/packetgen/header/http/headers.rb', line 75

def to_human
  @data
end

#to_sString

Get binary string.

Returns:

  • (String)

Since:

  • 2.2.0



63
64
65
66
67
68
69
70
71
# File 'lib/packetgen/header/http/headers.rb', line 63

def to_s
  return "\r\n" if @data.nil? || @data.empty?

  d = []
  @data.map do |k, v|
    d << "#{k}: #{v}"
  end
  d.join("\r\n") << "\r\n\r\n"
end