Class: Protocol::HTTP1::Body::Chunked

Inherits:
HTTP::Body::Readable
  • Object
show all
Defined in:
lib/protocol/http1/body/chunked.rb

Constant Summary collapse

CRLF =
"\r\n"

Instance Method Summary collapse

Constructor Details

#initialize(stream, headers) ⇒ Chunked

Returns a new instance of Chunked.



31
32
33
34
35
36
37
38
39
# File 'lib/protocol/http1/body/chunked.rb', line 31

def initialize(stream, headers)
  @stream = stream
  @finished = false
  
  @headers = headers
  
  @length = 0
  @count = 0
end

Instance Method Details

#close(error = nil) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/protocol/http1/body/chunked.rb', line 45

def close(error = nil)
  # We only close the connection if we haven't completed reading the entire body:
  unless @finished
    @stream.close
    @finished = true
  end
  
  super
end

#empty?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/protocol/http1/body/chunked.rb', line 41

def empty?
  @finished
end

#inspectObject



82
83
84
# File 'lib/protocol/http1/body/chunked.rb', line 82

def inspect
  "\#<#{self.class} #{@length} bytes read in #{@count} chunks>"
end

#readObject

Follows the procedure outlined in tools.ietf.org/html/rfc7230#section-4.1.3



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/protocol/http1/body/chunked.rb', line 56

def read
  return nil if @finished
  
  # It is possible this line contains chunk extension, so we use `to_i` to only consider the initial integral part:
  length = read_line.to_i(16)
  
  if length == 0
    @finished = true
    
    read_trailer
    
    return nil
  end
  
  # Read trailing CRLF:
  chunk = @stream.read(length + 2)
  
  # ...and chomp it off:
  chunk.chomp!(CRLF)
  
  @length += length
  @count += 1
  
  return chunk
end