Begin writing HTTP request headers early to detect disconnected clients
[unicorn.git] / lib / unicorn / http_response.rb
blob61563cd5a062170fe893c6a8da3295554cabdcdc
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                           response_start_sent=false)
23     status = CODES[status.to_i] || status
25     http_response_start = response_start_sent ? '' : 'HTTP/1.1 '
26     if headers
27       buf = "#{http_response_start}#{status}\r\n" \
28             "Date: #{httpdate}\r\n" \
29             "Status: #{status}\r\n" \
30             "Connection: close\r\n"
31       headers.each do |key, value|
32         next if %r{\A(?:Date\z|Connection\z)}i =~ key
33         if value =~ /\n/
34           # avoiding blank, key-only cookies with /\n+/
35           buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join
36         else
37           buf << "#{key}: #{value}\r\n"
38         end
39       end
40       socket.write(buf << CRLF)
41     end
43     body.each { |chunk| socket.write(chunk) }
44     ensure
45       body.respond_to?(:close) and body.close
46   end
47 end