如何在Ruby中从内存中HTTP发送流数据?

Sam*_*Sam 6 ruby upload post block stream

我想上传我在Ruby中运行时生成的数据,比如从块中提取上传内容.

我发现的所有示例仅显示如何在请求之前流式传输必须在磁盘上的文件,但我不想缓冲文件.

滚动我自己的套接字连接除了最佳解决方案是什么?

这是一个伪代码示例:

post_stream('127.0.0.1', '/stream/') do |body|
  generate_xml do |segment|
    body << segment
  end
end
Run Code Online (Sandbox Code Playgroud)

Rom*_*man 1

有一个 Net::HTTPGenericRequest#body_stream=( obj.should respond_to?(:read) )

你或多或少像这样使用它:


class Producer
  def initialize
   @mutex = Mutex.new
   @body = ''
  end

  def read(size)
    @mutex.synchronize {
      @body.slice!(0,size)
    }
  end

  def produce(str)
    @mutex.synchronize {
      @body << str
    }
  end
end

# Create a producer thread

req = Net::HTTP::Post.new(url.path)
req.body_stream = producer
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
Run Code Online (Sandbox Code Playgroud)