Sha256: 7071d313dac74c824b3932a2c0dbb25152254d8038370e22de11eb122647fb84

Contents?: true

Size: 1.67 KB

Versions: 3

Compression:

Stored size: 1.67 KB

Contents

# -*- encoding: binary -*-
module HTTP_Spew::Headers
  # :stopdoc:
  TR = %w(- _)
  REQUEST_METHOD = "REQUEST_METHOD"
  REQUEST_URI = "REQUEST_URI"
  CRLF = "\r\n"
  QUERY_STRING = "QUERY_STRING"
  PATH_INFO = "PATH_INFO"
  CONTENT_TYPE = "CONTENT_TYPE" # specified by Rack to be !/^HTTP_/
  # :startdoc:

  # regenerates the request_uri from a Rack +env+
  def request_uri(env)
    qs = env[QUERY_STRING]
    qs.size == 0 ? env[PATH_INFO] : "#{env[PATH_INFO]}?#{qs}"
  end
  module_function :request_uri

  # 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)
  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"
    uscore, dash = *TR
    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!(uscore, dash)
      req << "#{key}: #{value}\r\n"
    end
    if input
      req << (input.respond_to?(:size) ?
             "Content-Length: #{input.size}\r\n" :
             "Transfer-Encoding: chunked\r\n")
      ct = env[CONTENT_TYPE] and req << "Content-Type: #{ct}\r\n"
    end
    req << CRLF
    String === input ? (req << input) : [ req, input ]
  end
  module_function :env_to_headers
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
http_spew-0.4.0 lib/http_spew/headers.rb
http_spew-0.3.0 lib/http_spew/headers.rb
http_spew-0.2.0 lib/http_spew/headers.rb