20
20
def self.parse(socket, params={})
21
21
response = new(:status => socket.readline[9, 11].to_i)
22
block_given = block_given?
24
23
until ((data = socket.readline).chop!).empty?
25
24
key, value = data.split(/:\s*/, 2)
34
33
unless (params[:method].to_s.casecmp('HEAD') == 0) || NO_ENTITY.include?(response.status)
36
# don't pass stuff into a block if there was an error
37
if params[:expects] && ![*params[:expects]].include?(response.status)
35
# check to see if expects was set and matched
36
expected_status = !params.has_key?(:expects) || [*params[:expects]].include?(response.status)
38
# if expects matched and there is a block, use it
39
if expected_status && params.has_key?(:response_block)
42
40
if transfer_encoding_chunked
43
41
# 2 == "/r/n".length
44
42
while (chunk_size = socket.readline.chop!.to_i(16)) > 0
45
yield(socket.read(chunk_size + 2).chop!, nil, nil)
43
params[:response_block].call(socket.read(chunk_size + 2).chop!, nil, nil)
48
46
elsif remaining = content_length
49
47
remaining = content_length
50
48
while remaining > 0
51
yield(socket.read([CHUNK_SIZE, remaining].min), [remaining - CHUNK_SIZE, 0].max, content_length)
49
params[:response_block].call(socket.read([CHUNK_SIZE, remaining].min), [remaining - CHUNK_SIZE, 0].max, content_length)
52
50
remaining -= CHUNK_SIZE
55
53
while remaining = socket.read(CHUNK_SIZE)
56
yield(remaining, remaining.length, content_length)
54
params[:response_block].call(remaining, remaining.length, content_length)
57
else # no block or unexpected status
60
58
if transfer_encoding_chunked
61
59
while (chunk_size = socket.readline.chop!.to_i(16)) > 0
62
60
response.body << socket.read(chunk_size + 2).chop! # 2 == "/r/n".length