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

Inherits:
Object
  • Object
show all
Includes:
Types::Fieldable
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

Methods included from Types::Fieldable

#format_inspect, #sz, #type_name

Constructor Details

#initializeHeaders

Returns a new instance of Headers.

Since:

  • 2.2.0


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

def initialize
  @data = {}
end

Instance Attribute Details

#dataHash? (readonly) Also known as: to_h

Underlying Headers data (or nil).

Returns:

  • (Hash, nil)

Since:

  • 2.2.0


19
20
21
# File 'lib/packetgen/header/http/headers.rb', line 19

def data
  @data
end

Instance Method Details

#from_human(data) ⇒ self

Read human-readable data to populate header data.

Parameters:

  • data (String, Hash)

Returns:

  • (self)

Since:

  • 2.2.0


65
66
67
# File 'lib/packetgen/header/http/headers.rb', line 65

def from_human(data)
  read(data)
end

#given?Boolean

Check if any headers were given.

Returns:

  • (Boolean)

Since:

  • 2.2.0


71
72
73
74
75
# File 'lib/packetgen/header/http/headers.rb', line 71

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

  false
end

#read(s_or_h) ⇒ self

Populate object from a string or directly from a hash.

Parameters:

  • s_or_h (String, Hash)

Returns:

  • (self)

Since:

  • 2.2.0


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

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

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

#to_humanHash

Get a human readable string.

Returns:

  • (Hash)

Since:

  • 2.2.0


58
59
60
# File 'lib/packetgen/header/http/headers.rb', line 58

def to_human
  @data
end

#to_sString

Get binary string.

Returns:

  • (String)

Since:

  • 2.2.0


46
47
48
49
50
51
52
53
54
# File 'lib/packetgen/header/http/headers.rb', line 46

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