Module: HTTP_Spew::Headers

Included in:
Request
Defined in:
lib/http_spew/headers.rb

Class Method Summary collapse

Class Method Details

.env_to_headers(env, input) ⇒ Object

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)


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/http_spew/headers.rb', line 21

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) ⇒ Object

regenerates the request_uri from a Rack env



5
6
7
8
# File 'lib/http_spew/headers.rb', line 5

def request_uri(env)
  qs = env['QUERY_STRING']
  qs.size == 0 ? env['PATH_INFO'] : "#{env['PATH_INFO']}?#{qs}"
end