http_response: simplify regular expression
[unicorn.git] / lib / unicorn / http_response.rb
blob801bf9a2c2c46b85d1fbc319932c94ab42e84452
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   def err_response(code, response_start_sent)
21     "#{response_start_sent ? '' : 'HTTP/1.1 '}#{CODES[code]}\r\n\r\n"
22   end
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     hijack = nil
29     http_response_start = response_start_sent ? '' : 'HTTP/1.1 '
30     if headers
31       buf = "#{http_response_start}#{CODES[status.to_i] || status}\r\n" \
32             "Date: #{httpdate}\r\n" \
33             "Connection: close\r\n"
34       headers.each do |key, value|
35         case key
36         when %r{\A(?:Date|Connection)\z}i
37           next
38         when "rack.hijack"
39           # This should only be hit under Rack >= 1.5, as this was an illegal
40           # key in Rack < 1.5
41           hijack = value
42         else
43           if value =~ /\n/
44             # avoiding blank, key-only cookies with /\n+/
45             buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join
46           else
47             buf << "#{key}: #{value}\r\n"
48           end
49         end
50       end
51       socket.write(buf << CRLF)
52     end
54     if hijack
55       body = nil # ensure we do not close body
56       hijack.call(socket)
57     else
58       body.each { |chunk| socket.write(chunk) }
59     end
60   ensure
61     body.respond_to?(:close) and body.close
62   end
63 end