documentation cleanup/reduction
[unicorn.git] / lib / unicorn / http_response.rb
blobb781e20f175bd04a8d24b78f7fd188a3d1827940
1 # -*- encoding: binary -*-
2 # :enddoc:
3 # Writes a Rack response to your client using the HTTP/1.1 specification.
4 # You use it by simply doing:
6 #   status, headers, body = rack_app.call(env)
7 #   http_response_write(socket, status, headers, body)
9 # Most header correctness (including Content-Length and Content-Type)
10 # is the job of Rack, with the exception of the "Date" and "Status" header.
11 module Unicorn::HttpResponse
13   # Every standard HTTP code mapped to the appropriate message.
14   CODES = Rack::Utils::HTTP_STATUS_CODES.inject({}) { |hash,(code,msg)|
15     hash[code] = "#{code} #{msg}"
16     hash
17   }
18   CRLF = "\r\n"
20   # writes the rack_response to socket as an HTTP response
21   def http_response_write(socket, status, headers, body)
22     status = CODES[status.to_i] || status
24     if headers
25       buf = "HTTP/1.1 #{status}\r\n" \
26             "Date: #{httpdate}\r\n" \
27             "Status: #{status}\r\n" \
28             "Connection: close\r\n"
29       headers.each do |key, value|
30         next if %r{\A(?:Date\z|Connection\z)}i =~ key
31         if value =~ /\n/
32           # avoiding blank, key-only cookies with /\n+/
33           buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join
34         else
35           buf << "#{key}: #{value}\r\n"
36         end
37       end
38       socket.write(buf << CRLF)
39     end
41     body.each { |chunk| socket.write(chunk) }
42     ensure
43       body.respond_to?(:close) and body.close
44   end
45 end