Class: Rig::HTTPResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/rig/http_response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ HTTPResponse

Returns a new instance of HTTPResponse.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rig/http_response.rb', line 6

def initialize response
  parts = response.split(CRLF + CRLF)
  @header = parts.delete_at( 0 )
  @status = @header.match(/HTTP\/\d.\d\s(\d\d\d)/)[1]
  @body   = parts.join

  parse_header

  if @header["Transfer-Encoding"] == "chunked"
    parsed_body = ""
    @body = StringIO.new( @body )
    read_chunked( parsed_body )

    @body = parsed_body
  end
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



4
5
6
# File 'lib/rig/http_response.rb', line 4

def body
  @body
end

#headerObject (readonly)

Returns the value of attribute header.



4
5
6
# File 'lib/rig/http_response.rb', line 4

def header
  @header
end

Instance Method Details

#parse_headerObject



27
28
29
30
31
32
33
34
35
36
# File 'lib/rig/http_response.rb', line 27

def parse_header
  status_line = @header[/HTTP\/\d\.\d\s\d\d\d.+\r\n/]
  @header = @header.gsub(status_line, "Status: #{status_line}")
  @header = @header.split(CRLF)
  @header = @header.map { |element| element.split(": ") }
  @header = @header.inject({}) do |result, element|
    result[element.first] = element.last
    result
  end
end

#read_chunked(dest) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rig/http_response.rb', line 38

def read_chunked(dest)
  len = nil
  total = 0
  while true
    line = @body.readline
    hexlen = line.slice(/[0-9a-fA-F]+/) or
      raise HTTPBadResponse, "wrong chunk size line: #{line}"
    len = hexlen.hex
    break if len == 0
    @body.read len, dest; total += len
    @body.read 2   # \r\n
  end
end

#statusObject



23
24
25
# File 'lib/rig/http_response.rb', line 23

def status
  @status ? @status.to_i : 666
end