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}"
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
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|Status\z|Connection\z)}i =~ key
31 # avoiding blank, key-only cookies with /\n+/
32 buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join
34 buf << "#{key}: #{value}\r\n"
37 socket.write(buf << CRLF)
40 body.each { |chunk| socket.write(chunk) }
42 body.respond_to?(:close) and body.close