blob: 6afa4f98c9543db2c9da4878aec467eb6c4aacb7 (
plain)
1
2
3
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
52
53
54
55
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
81
82
83
84
85
86
|
# -*- frozen-string-literal: true -*-
module Plum
class Response
# The response headers
# @return [Hash<String, String>]
attr_reader :headers
# @api private
def initialize
@body = Queue.new
@finished = false
@failed = false
@body_read = false
end
# Return the HTTP status code.
# @return [String] the HTTP status code
def status
@headers && @headers[":status"]
end
# Returns the header value that correspond to the header name.
# @param key [String] the header name
# @return [String] the header value
def [](key)
@headers[key.to_s.downcase]
end
# Returns whether the response is complete or not.
# @return [Boolean]
def finished?
@finished
end
# Returns whether the request has failed or not.
# @return [Boolean]
def failed?
@failed
end
# Yields a chunk of the response body until EOF.
# @yield [chunk] A chunk of the response body.
def each_chunk(&block)
raise "Body already read" if @body_read
@body_read = true
while chunk = @body.pop
if chunk == :failed
raise EOFError
else
yield chunk
end
end
end
# Returns the complete response body. Use #each_body instead if the body can be very large.
# @return [String] the whole response body
def body
body = String.new
each_chunk { |chunk| body << chunk }
body
end
# @api private
def _headers(raw_headers)
# response headers should not have duplicates
@headers = raw_headers.to_h.freeze
end
# @api private
def _chunk(chunk)
@body << chunk
end
# @api private
def _finish
@finished = true
@body << nil # @body.close is not implemented in Ruby 2.2
end
# @api private
def _fail
@failed = true
@body << :failed
end
end
end
|