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