# frozen_string_literal: true # This file is part of PacketGen # See https://github.com/sdaubert/packetgen for more informations # Copyright (C) 2016 Sylvain Daubert # This program is published under MIT license. module PacketGen module Header # @since 2.2.0 module HTTP # @abstract Base class for HTTP headers. # @author Kent 'picat' Gruber class Headers include Inspectable # Underlying Headers data (or nil). # @return [Hash, nil] attr_reader :data alias to_h data def initialize @data = nil end # Populate object from a string or directly from a hash. # @param [String, Hash] s_or_h # @return [self] 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 # Get binary string. # @return [String] 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 # Get a human readable string. # @return [Hash] def to_human @data end alias format_inspect to_human # Read human-readable data to populate header data. # @param [String, Hash] data # @return [self] def from_human(data) read(data) end # Check if any headers were given. # @return [Boolean] def given? return true unless @data.nil? || @data.empty? false end end end end end