added stream (for text/event-stream) first draft plugin; allowing bodyless responses (which the parser won't be able to complete) to make an early exit

This commit is contained in:
HoneyryderChuck 2018-02-03 20:00:25 +00:00
parent 2ef24af0a9
commit 2e065c9d4e
3 changed files with 44 additions and 5 deletions

View File

@ -86,16 +86,18 @@ module HTTPX
log { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{v}" }.join("\n") }
request.response = response
# parser can't say if it's parsing GET or HEAD,
# call the completeness callback manually
dispatch if request.verb == :head ||
request.verb == :connect
@has_response = true if response.complete?
end
def on_body(chunk)
log { "-> DATA: #{chunk.bytesize} bytes..." }
log(2) { "-> #{chunk.inspect}" }
@requests.first.response << chunk
response = @requests.first.response
response << chunk
dispatch if response.complete?
end
def on_message_complete

View File

@ -0,0 +1,33 @@
# frozen_string_literal: true
module HTTPX
module Plugins
module Stream
module InstanceMethods
def stream
headers("accept" => "text/event-stream",
"cache-control" => "no-cache")
end
end
module ResponseMethods
def complete?
super ||
stream? &&
@stream_complete
end
def stream?
@headers["content-type"].start_with?("text/event-stream")
end
def <<(data)
res = super
@stream_complete = true if String(data).end_with?("\n\n")
res
end
end
end
register_plugin :stream, Stream
end
end

View File

@ -52,6 +52,10 @@ module HTTPX
ContentType.parse(@headers["content-type"])
end
def complete?
bodyless?
end
def inspect
"#<Response:#{object_id} @status=#{@status} @headers=#{@headers}>"
end