class Kcar::Response

This may be used to generate a Rack response synchronously.

Constants

READ_SIZE

By default we readpartial at most 16K off a socket at once

Public Class Methods

new(sock, hdr = {}, unchunk = true) click to toggle source

initializes a socket, sock must respond to the “readpartial” method. unchunk may be set to disable transparent unchunking hdr may be a Hash, Array, or Rack::Utils::HeaderHash

# File lib/kcar/response.rb, line 16
def initialize(sock, hdr = {}, unchunk = true)
  @sock, @hdr, @unchunk, @buf =  sock, hdr, unchunk, ""
  @parser = Kcar::Parser.new
end

Public Instance Methods

close() click to toggle source

this is expected to be called by our Rack server, it will close our given sock object if keepalive is not used otherwise it will just reset the parser and clear the header object

# File lib/kcar/response.rb, line 54
def close
  @parser.keepalive? ? reset : @sock.close
end
each() { |buf| ... } click to toggle source

this method allows our Kcar::Response object to be used as a Rack response body. It may only be called once (usually by a Rack server) as it streams the response body off the our socket object.

# File lib/kcar/response.rb, line 61
def each
  return if @parser.body_eof?
  if @unchunk
    @parser.chunked? ? each_unchunk { |buf| yield buf } :
                       each_identity { |buf| yield buf }
  else
    @parser.chunked? ? each_rechunk { |buf| yield buf } :
                       each_identity { |buf| yield buf }
  end
end
rack() click to toggle source

returns a 3-element array suitable for use as a Rack response:

[ status, headers, body ]

this method will not return until the response headers are fully parsed, but the body returned will be this Kcar::Response handler itself. It is not guaranteed that trailers will be stored in the returned header

# File lib/kcar/response.rb, line 46
def rack
  @unchunk = false
  read
end
read() click to toggle source

returns a 3-element array that resembles a Rack response, but is more useful for additional processing by other code.

[ status, headers, body ]

Use Kcar::Response#rack if you want to guarantee a proper Rack response.

this method will not return until the response headers are fully parsed, but the body returned will be this Kcar::Response handler itself. unchunk must be true to guarantee trailers will be stored in the returned header object

# File lib/kcar/response.rb, line 32
def read
  @buf << @sock.readpartial(READ_SIZE) if @buf.empty?
  until response = @parser.headers(@hdr, @buf)
    @buf << @sock.readpartial(READ_SIZE)
  end
  response << self
end