Class: Excon::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/excon/response.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Response

Returns a new instance of Response.



55
56
57
58
59
# File 'lib/excon/response.rb', line 55

def initialize(attributes = {})
  @body    = attributes[:body] || ''
  @headers = attributes[:headers] || {}
  @status  = attributes[:status]
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



53
54
55
# File 'lib/excon/response.rb', line 53

def body
  @body
end

#headersObject

Returns the value of attribute headers.



53
54
55
# File 'lib/excon/response.rb', line 53

def headers
  @headers
end

#statusObject

Returns the value of attribute status.



53
54
55
# File 'lib/excon/response.rb', line 53

def status
  @status
end

Class Method Details

.parse(socket, params = {}, &block) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/excon/response.rb', line 4

def self.parse(socket, params = {}, &block)
  if params[:block]
    print "  \e[33m[WARN] params[:block] is deprecated, please pass the block to the request\e[0m"
    block = params[:block]
  end

  response = new

  response.status = socket.readline[9..11].to_i
  while true
    data = socket.readline.chop!
    unless data.empty?
      key, value = data.split(': ')
      response.headers[key] = value
    else
      break
    end
  end

  unless params[:method] == 'HEAD'
    if !block || (params[:expects] && ![*params[:expects]].include?(response.status))
      response.body = ''
      block = lambda { |chunk| response.body << chunk }
    end

    if response.headers['Connection'] == 'close'
      block.call(socket.read)
    elsif response.headers['Content-Length']
      remaining = response.headers['Content-Length'].to_i
      while remaining > 0
        block.call(socket.read([CHUNK_SIZE, remaining].min))
        remaining -= CHUNK_SIZE
      end
    elsif response.headers['Transfer-Encoding'] == 'chunked'
      while true
        chunk_size = socket.readline.chop!.to_i(16)
        chunk = socket.read(chunk_size + 2).chop! # 2 == "/r/n".length
        if chunk_size > 0
          block.call(chunk)
        else
          break
        end
      end
    end
  end

  response
end