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.



14
15
16
17
18
19
20
21
22
# File 'lib/protocol/http1/body/chunked.rb', line 14

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

Instance Method Details

#close(error = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/protocol/http1/body/chunked.rb', line 28

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)


24
25
26
# File 'lib/protocol/http1/body/chunked.rb', line 24

def empty?
	@finished
end

#inspectObject



65
66
67
# File 'lib/protocol/http1/body/chunked.rb', line 65

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/protocol/http1/body/chunked.rb', line 39

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