module HTTP_Spew::Headers

Public Class Methods

env_to_headers(env, input) click to toggle source

converts a Rack env into an HTTP header buffer If input is a string, this appends input to the header buffer so the client can avoid extra writes. If input is an IO-like object, it is returned as the second element of an array.

This, the following code always works and may be used to clobber input if it is merged into buf

buf, input = env_to_headers(env, input)
# File lib/http_spew/headers.rb, line 20
def env_to_headers(env, input)
  req = "#{env['REQUEST_METHOD']} " \
        "#{env['REQUEST_URI'] || request_uri(env)} HTTP/1.1\r\n" \
        "Connection: close\r\n"
  env.each do |key,value|
    %r{\AHTTP_(\w+)\z} =~ key or next
    key = $1
    %r{\A(?:VERSION|EXPECT|TRANSFER_ENCODING|CONNECTION|KEEP_ALIVE)\z}x =~
      key and next

    key.tr!('_'.freeze, '-'.freeze)
    req << "#{key}: #{value}\r\n"
  end
  if input
    req << (input.respond_to?(:size) ?
           "Content-Length: #{input.size}\r\n" :
           "Transfer-Encoding: chunked\r\n".freeze)
    ct = env['CONTENT_TYPE'] and req << "Content-Type: #{ct}\r\n"
  end
  req << "\r\n".freeze
  String === input ? (req << input) : [ req, input ]
end
request_uri(env) click to toggle source

regenerates the request_uri from a Rack env

# File lib/http_spew/headers.rb, line 4
def request_uri(env)
  qs = env['QUERY_STRING']
  qs.size == 0 ? env['PATH_INFO'] : "#{env['PATH_INFO']}?#{qs}"
end

Private Instance Methods

env_to_headers(env, input) click to toggle source

converts a Rack env into an HTTP header buffer If input is a string, this appends input to the header buffer so the client can avoid extra writes. If input is an IO-like object, it is returned as the second element of an array.

This, the following code always works and may be used to clobber input if it is merged into buf

buf, input = env_to_headers(env, input)
# File lib/http_spew/headers.rb, line 20
def env_to_headers(env, input)
  req = "#{env['REQUEST_METHOD']} " \
        "#{env['REQUEST_URI'] || request_uri(env)} HTTP/1.1\r\n" \
        "Connection: close\r\n"
  env.each do |key,value|
    %r{\AHTTP_(\w+)\z} =~ key or next
    key = $1
    %r{\A(?:VERSION|EXPECT|TRANSFER_ENCODING|CONNECTION|KEEP_ALIVE)\z}x =~
      key and next

    key.tr!('_'.freeze, '-'.freeze)
    req << "#{key}: #{value}\r\n"
  end
  if input
    req << (input.respond_to?(:size) ?
           "Content-Length: #{input.size}\r\n" :
           "Transfer-Encoding: chunked\r\n".freeze)
    ct = env['CONTENT_TYPE'] and req << "Content-Type: #{ct}\r\n"
  end
  req << "\r\n".freeze
  String === input ? (req << input) : [ req, input ]
end
request_uri(env) click to toggle source

regenerates the request_uri from a Rack env

# File lib/http_spew/headers.rb, line 4
def request_uri(env)
  qs = env['QUERY_STRING']
  qs.size == 0 ? env['PATH_INFO'] : "#{env['PATH_INFO']}?#{qs}"
end