1 # -*- encoding: binary -*-
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}"
20 def err_response(code, response_start_sent)
21 "#{response_start_sent ? '' : 'HTTP/1.1 '}#{CODES[code]}\r\n\r\n"
24 # writes the rack_response to socket as an HTTP response
25 def http_response_write(socket, status, headers, body,
26 response_start_sent=false)
27 status = CODES[status.to_i] || status
29 http_response_start = response_start_sent ? '' : 'HTTP/1.1 '
31 buf = "#{http_response_start}#{status}\r\n" \
32 "Date: #{httpdate}\r\n" \
33 "Status: #{status}\r\n" \
34 "Connection: close\r\n"
35 headers.each do |key, value|
36 next if %r{\A(?:Date\z|Connection\z)}i =~ key
38 # avoiding blank, key-only cookies with /\n+/
39 buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join
41 buf << "#{key}: #{value}\r\n"
44 socket.write(buf << CRLF)
47 body.each { |chunk| socket.write(chunk) }
49 body.respond_to?(:close) and body.close