added support for chunking requests (sadly, not being able to test it well...)

This commit is contained in:
HoneyryderChuck 2017-12-09 01:11:24 +00:00
parent e4fee5cf6f
commit c9b632fb55
5 changed files with 79 additions and 4 deletions

View File

@ -117,8 +117,22 @@ module HTTPX
raise Error, "cannot determine size of body: #{@body.inspect}"
end
end
def stream(body)
encoded = body
if chunked?
encoded = Transcoder::Chunker.encode(body)
end
encoded
end
def chunked?
@headers["transfer-encoding"] == "chunked"
end
end
private
class ProcIO
def initialize(block)
@block = block

View File

@ -9,3 +9,4 @@ end
require "httpx/transcoder/body"
require "httpx/transcoder/form"
require "httpx/transcoder/json"
require "httpx/transcoder/chunker"

View File

@ -7,11 +7,7 @@ module HTTPX::Transcoder
class Encoder
extend Forwardable
def_delegator :@raw, :to_str
def_delegator :@raw, :to_s
def_delegator :@raw, :force_encoding
def initialize(body)
@raw = body
@ -20,6 +16,10 @@ module HTTPX::Transcoder
def bytesize
if @raw.respond_to?(:bytesize)
@raw.bytesize
elsif @raw.respond_to?(:to_ary)
@raw.map(&:bytesize).reduce(0, :+)
elsif @raw.respond_to?(:each)
Float::INFINITY
elsif @raw.respond_to?(:size)
@raw.size
else
@ -30,6 +30,20 @@ module HTTPX::Transcoder
def content_type
"application/octet-stream"
end
private
def respond_to_missing?(meth, *args)
@raw.respond_to?(meth, *args) || super
end
def method_missing(meth, *args, &block)
if @raw.respond_to?(meth)
@raw.__send__(meth, *args, &block)
else
super
end
end
end
def encode(body)

View File

@ -0,0 +1,35 @@
# frozen_string_literal: true
module HTTPX::Transcoder
module Chunker
module_function
class Encoder
extend Forwardable
CRLF = "\r\n"
def initialize(body)
@raw = body
end
def each
return enum_for(__method__) unless block_given?
@raw.each do |chunk|
yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
end
yield "0#{CRLF}#{CRLF}"
end
def respond_to_missing?(meth, *args)
@raw.respond_to?(meth, *args) || super
end
end
def encode(json)
Encoder.new(json)
end
end
register "json", JSON
end

View File

@ -71,6 +71,17 @@ class HTTP1Test < Minitest::Spec
assert body.key?("data")
assert body["data"] == "data"
end
#define_method :"test_#{meth}_chunked_body_params" do
# uri = build_uri("/#{meth}")
# response = HTTPX.headers("transfer-encoding" => "chunked")
# .send(meth, uri, body: %w[this is a chunked response])
# assert response.status == 200, "status is unexpected"
# body = json_body(response)
# assert body["headers"]["Transfer-Encoding"] == "chunked"
# assert body.key?("data")
# assert body["data"] == "thisisachunkedresponse"
#end
end
def test_http_headers