# encoding: utf-8

require 'httpkit'

class EchoServer
  def serve(request, served)
    response = streaming_response

    # We start sending the response even we started writing its body. This is
    # not mandatory, but it delivers the response to client as quickly as
    # possible.
    served.fulfill(response)

    serialize(request, response)
    request.closed { response.close }
  end

  private

  def streaming_response
    HTTPkit::Response.new(200,
                          { 'Content-Type' => 'application/octet-stream' },
                          HTTPkit::Body.new)
  end

  # This re-serializes the whole request directly into the response body.
  def serialize(request, response)
    writer     = response.body.method(:write)
    serializer = HTTPkit::Serializer.new(request, writer)
    serializer.serialize
  end
end

HTTPkit.run do
  address = '127.0.0.1'
  port = HTTPkit.random_port(address)

  HTTPkit::Server.start(address: address, port: port,
                        handlers: [HTTPkit::Server::KeepAliveHandler.new,
                                   EchoServer.new])

  body = HTTPkit.request(:get, "http://#{address}:#{port}").body
  body.to_s.each_line { |line| p line }
end