class Knjappserver::Httpsession::Http_response

This object writes headers, trailing headers, status headers and more for HTTP-sessions.

Constants

NL
STATUS_CODES

Attributes

cgroup[RW]
chunked[RW]
headers[RW]
headers_sent[RW]
headers_trailing[RW]
http_version[RW]
nl[RW]
socket[RW]
status[RW]

Public Class Methods

new(args) click to toggle source
# File lib/include/class_httpsession_http_response.rb, line 28
def initialize(args)
  @chunked = false
  @socket = args[:socket]
end

Public Instance Methods

header(key, val) click to toggle source
# File lib/include/class_httpsession_http_response.rb, line 61
def header(key, val)
  lines = val.to_s.count("\n") + 1
  raise "Value contains more lines than 1 (#{lines})." if lines > 1
  
  if !@headers_sent
    @headers[key.to_s.downcase] = [key, val]
  else
    raise "Headers already sent and given header was not in trailing headers: '#{key}'." if @trailers.index(key) == nil
    @headers_trailing[key.to_s.downcase] = [key, val]
  end
end
header_str() click to toggle source
# File lib/include/class_httpsession_http_response.rb, line 77
def header_str
  if @http_version == "1.0"
    res = "HTTP/1.0 #{@status}"
  else
    res = "HTTP/1.1 #{@status}"
  end
  
  code = STATUS_CODES[@status]
  res << " #{code}" if code
  res << NL
  
  @headers.each do |key, val|
    res << "#{val[0]}: #{val[1]}#{NL}"
  end
  
  if @http_version == "1.1"
    @headers_11.each do |key, val|
      res << "#{key}: #{val}#{NL}"
    end
    
    @trailers.each do |trailer|
      res << "Trailer: #{trailer}#{NL}"
    end
  end
  
  @cookies.each do |cookie|
    res << "Set-Cookie: #{Knj::Web.cookie_str(cookie)}#{NL}"
  end
  
  res << NL
  
  return res
end
reset(args) click to toggle source
# File lib/include/class_httpsession_http_response.rb, line 33
def reset(args)
  @status = 200
  @http_version = args[:http_version]
  @close = args[:close]
  @fileobj = nil
  @close = true if @http_version == "1.0"
  @trailers = []
  
  @headers_sent = false
  @headers_trailing = {}
  
  @headers = {
    "date" => ["Date", Time.now.httpdate]
  }
  
  @headers_11 = {
    "Connection" => "Keep-Alive",
    "Transfer-Encoding" => "chunked"
  }
  
  #Socket-timeout is currently broken in JRuby.
  if RUBY_ENGINE != "jruby"
    @headers_11["Keep-Alive"] = "timeout=15, max=30"
  end
  
  @cookies = []
end
write() click to toggle source
# File lib/include/class_httpsession_http_response.rb, line 111
def write
  @headers_sent = true
  @socket.write(self.header_str)
  
  if @status == 304
    #do nothing.
  else
    if @chunked
      @cgroup.write_to_socket
      @socket.write("0#{NL}")
      
      @headers_trailing.each do |header_id_str, header|
        @socket.write("#{header[0]}: #{header[1]}#{NL}")
      end
      
      @socket.write(NL)
    else
      @cgroup.write_to_socket
      @socket.write("#{NL}#{NL}")
    end
  end
  
  @socket.close if @close
end