blob: 8270e95c29357bed453e780f8582238834a0553c (
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
87
88
|
# -*- 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 = []
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
# Set callback tha called when received a chunk of response body.
# @yield [chunk] A chunk of the response body.
def on_chunk(&block)
raise "Body already read" if @on_chunk
@on_chunk = block
unless @body.empty?
@body.each(&block)
@body.clear
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
raise "Body already read" if @on_chunk
if finished?
@body.join
else
raise "Response body is not complete"
end
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)
if @on_chunk
@on_chunk.call(chunk)
else
@body << chunk
end
end
# @api private
def _finish
@finished = true
end
# @api private
def _fail(ex)
@failed = true
end
end
end
|