response.rb 13.2 KB
Newer Older
1 2 3 4
require "active_support/core_ext/module/attribute_accessors"
require "action_dispatch/http/filter_redirect"
require "action_dispatch/http/cache"
require "monitor"
5

6
module ActionDispatch # :nodoc:
7 8 9 10 11
  # Represents an HTTP response generated by a controller action. Use it to
  # retrieve the current state of the response, or customize the response. It can
  # either represent a real HTTP response (i.e. one that is meant to be sent
  # back to the web browser) or a TestResponse (i.e. one that is generated
  # from integration tests).
P
Pratik Naik 已提交
12
  #
13
  # \Response is mostly a Ruby on \Rails framework implementation detail, and
14 15 16 17
  # should never be used directly in controllers. Controllers should use the
  # methods defined in ActionController::Base instead. For example, if you want
  # to set the HTTP response's content MIME type, then use
  # ActionControllerBase#headers instead of Response#headers.
P
Pratik Naik 已提交
18
  #
19
  # Nevertheless, integration tests may want to inspect controller responses in
20
  # more detail, and that's when \Response can be useful for application
21
  # developers. Integration test methods such as
J
Joshua Peek 已提交
22 23
  # ActionDispatch::Integration::Session#get and
  # ActionDispatch::Integration::Session#post return objects of type
24
  # TestResponse (which are of course also of type \Response).
P
Pratik Naik 已提交
25
  #
26
  # For example, the following demo integration test prints the body of the
P
Pratik Naik 已提交
27 28
  # controller response to the console:
  #
J
Joshua Peek 已提交
29
  #  class DemoControllerTest < ActionDispatch::IntegrationTest
P
Pratik Naik 已提交
30 31
  #    def test_print_root_path_to_console
  #      get('/')
A
Alexey Vakhov 已提交
32
  #      puts response.body
P
Pratik Naik 已提交
33 34
  #    end
  #  end
35
  class Response
36 37 38 39 40 41
    class Header < DelegateClass(Hash) # :nodoc:
      def initialize(response, header)
        @response = response
        super(header)
      end

42
      def []=(k, v)
43
        if @response.sending? || @response.sent?
44
          raise ActionDispatch::IllegalStateError, "header already sent"
45 46 47 48 49 50 51 52 53 54 55 56 57 58
        end

        super
      end

      def merge(other)
        self.class.new @response, __getobj__.merge(other)
      end

      def to_hash
        __getobj__.dup
      end
    end

59 60 61 62
    # The request that the response is responding to.
    attr_accessor :request

    # The HTTP status code.
63
    attr_reader :status
64

65
    # Get headers for this response.
66
    attr_reader :header
67

68 69
    alias_method :headers,  :header

70
    delegate :[], :[]=, to: :@header
R
Ryan T. Hosford 已提交
71 72 73 74 75 76 77

    def each(&block)
      sending!
      x = @stream.each(&block)
      sent!
      x
    end
78

79 80 81
    CONTENT_TYPE = "Content-Type".freeze
    SET_COOKIE   = "Set-Cookie".freeze
    LOCATION     = "Location".freeze
82
    NO_CONTENT_CODES = [100, 101, 102, 204, 205, 304]
S
Santiago Pastorino 已提交
83

84
    cattr_accessor(:default_charset) { "utf-8" }
E
Egor Homakov 已提交
85
    cattr_accessor(:default_headers)
86

87
    include Rack::Response::Helpers
88
    # Aliasing these off because AD::Http::Cache::Response defines them.
89 90 91
    alias :_cache_control :cache_control
    alias :_cache_control= :cache_control=

92
    include ActionDispatch::Http::FilterRedirect
93
    include ActionDispatch::Http::Cache::Response
94
    include MonitorMixin
95

96 97 98 99 100
    class Buffer # :nodoc:
      def initialize(response, buf)
        @response = response
        @buf      = buf
        @closed   = false
101 102 103 104 105
        @str_body = nil
      end

      def body
        @str_body ||= begin
106
          buf = ""
107
          each { |chunk| buf << chunk }
R
Ryan T. Hosford 已提交
108 109
          buf
        end
110 111 112 113 114
      end

      def write(string)
        raise IOError, "closed stream" if closed?

115
        @str_body = nil
116 117 118 119 120
        @response.commit!
        @buf.push string
      end

      def each(&block)
R
Ryan T. Hosford 已提交
121 122 123 124 125 126 127
        if @str_body
          return enum_for(:each) unless block_given?

          yield @str_body
        else
          each_chunk(&block)
        end
128 129
      end

130 131 132
      def abort
      end

133 134 135 136 137 138 139 140
      def close
        @response.commit!
        @closed = true
      end

      def closed?
        @closed
      end
R
Ryan T. Hosford 已提交
141 142 143 144

      private

        def each_chunk(&block)
145
          @buf.each(&block)
R
Ryan T. Hosford 已提交
146
        end
147 148
    end

149 150 151 152 153 154 155 156 157
    def self.create(status = 200, header = {}, body = [], default_headers: self.default_headers)
      header = merge_default_headers(header, default_headers)
      new status, header, body
    end

    def self.merge_default_headers(original, default)
      default.respond_to?(:merge) ? default.merge(original) : original
    end

158
    # The underlying body, as a streamable object.
159 160
    attr_reader :stream

161
    def initialize(status = 200, header = {}, body = [])
162 163
      super()

164
      @header = Header.new(self, header)
E
Egor Homakov 已提交
165

166
      self.body, self.status = body, status
167

168 169
      @cv           = new_cond
      @committed    = false
170 171
      @sending      = false
      @sent         = false
J
Joshua Peek 已提交
172

173 174 175 176
      prepare_cache_control!

      yield self if block_given?
    end
177

178
    def has_header?(key);   headers.key? key;   end
179 180 181 182
    def get_header(key);    headers[key];       end
    def set_header(key, v); headers[key] = v;   end
    def delete_header(key); headers.delete key; end

183 184 185 186 187 188
    def await_commit
      synchronize do
        @cv.wait_until { @committed }
      end
    end

189 190 191 192
    def await_sent
      synchronize { @cv.wait_until { @sent } }
    end

193 194
    def commit!
      synchronize do
195
        before_committed
196 197 198 199 200
        @committed = true
        @cv.broadcast
      end
    end

201 202 203 204 205 206
    def sending!
      synchronize do
        before_sending
        @sending = true
        @cv.broadcast
      end
207 208
    end

209 210 211 212 213 214 215 216 217 218 219
    def sent!
      synchronize do
        @sent = true
        @cv.broadcast
      end
    end

    def sending?;   synchronize { @sending };   end
    def committed?; synchronize { @committed }; end
    def sent?;      synchronize { @sent };      end

220
    # Sets the HTTP status code.
221
    def status=(status)
222
      @status = Rack::Utils.status_code(status)
223 224
    end

225
    # Sets the HTTP content type.
S
Santiago Pastorino 已提交
226
    def content_type=(content_type)
227 228
      return unless content_type
      new_header_info = parse_content_type(content_type.to_s)
229
      prev_header_info = parsed_content_type_header
230 231 232
      charset = new_header_info.charset || prev_header_info.charset
      charset ||= self.class.default_charset unless prev_header_info.mime_type
      set_content_type new_header_info.mime_type, charset
233 234
    end

A
Aaron Patterson 已提交
235 236 237 238 239 240 241 242
    # Sets the HTTP response's content MIME type. For example, in the controller
    # you could write this:
    #
    #  response.content_type = "text/plain"
    #
    # If a character set has been defined for this response (see charset=) then
    # the character set information will also be included in the content type
    # information.
243

A
Aaron Patterson 已提交
244
    def content_type
245
      parsed_content_type_header.mime_type
246 247 248 249 250 251
    end

    def sending_file=(v)
      if true == v
        self.charset = false
      end
S
Santiago Pastorino 已提交
252 253
    end

254
    # Sets the HTTP character set. In case of +nil+ parameter
A
Akira Matsuda 已提交
255
    # it sets the charset to utf-8.
256 257
    #
    #   response.charset = 'utf-16' # => 'utf-16'
258
    #   response.charset = nil      # => 'utf-8'
259
    def charset=(charset)
260
      header_info = parsed_content_type_header
261
      if false == charset
262
        set_header CONTENT_TYPE, header_info.mime_type
263
      else
264
        content_type = header_info.mime_type
265
        set_content_type content_type, charset || self.class.default_charset
266
      end
267 268
    end

A
Aaron Patterson 已提交
269 270 271
    # The charset of the response. HTML wants to know the encoding of the
    # content you're giving them, so we need to send that along.
    def charset
272
      header_info = parsed_content_type_header
A
Aaron Patterson 已提交
273 274 275
      header_info.charset || self.class.default_charset
    end

276
    # The response code of the request.
277
    def response_code
278
      @status
279 280
    end

281
    # Returns a string to ensure compatibility with <tt>Net::HTTPResponse</tt>.
282
    def code
283
      @status.to_s
284 285
    end

286 287
    # Returns the corresponding message for the current HTTP status code:
    #
288 289 290 291 292
    #   response.status = 200
    #   response.message # => "OK"
    #
    #   response.status = 404
    #   response.message # => "Not Found"
293
    #
294
    def message
295
      Rack::Utils::HTTP_STATUS_CODES[@status]
296
    end
297
    alias_method :status_message, :message
298

299
    # Returns the content of the response as a string. This contains the contents
300
    # of any calls to <tt>render</tt>.
301
    def body
302
      @stream.body
303
    end
304

305 306 307 308
    def write(string)
      @stream.write string
    end

309
    # Allows you to manually set or override the response body.
310
    def body=(body)
311 312 313
      if body.respond_to?(:to_path)
        @stream = body
      else
314 315 316
        synchronize do
          @stream = build_buffer self, munge_body_object(body)
        end
317
      end
318 319
    end

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    # Avoid having to pass an open file handle as the response body.
    # Rack::Sendfile will usually intercept the response and uses
    # the path directly, so there is no reason to open the file.
    class FileBody #:nodoc:
      attr_reader :to_path

      def initialize(path)
        @to_path = path
      end

      def body
        File.binread(to_path)
      end

      # Stream the file's contents if Rack::Sendfile isn't present.
      def each
336
        File.open(to_path, "rb") do |file|
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
          while chunk = file.read(16384)
            yield chunk
          end
        end
      end
    end

    # Send the file stored at +path+ as the response body.
    def send_file(path)
      commit!
      @stream = FileBody.new(path)
    end

    def reset_body!
      @stream = build_buffer(self, [])
    end

354
    def body_parts
355 356 357
      parts = []
      @stream.each { |x| parts << x }
      parts
D
Initial  
David Heinemeier Hansson 已提交
358 359
    end

360
    # The location header we'll be responding with.
361
    alias_method :redirect_url, :location
362

363
    def close
364
      stream.close if stream.respond_to?(:close)
365 366
    end

367 368 369 370 371 372 373 374 375 376 377
    def abort
      if stream.respond_to?(:abort)
        stream.abort
      elsif stream.respond_to?(:close)
        # `stream.close` should really be reserved for a close from the
        # other direction, but we must fall back to it for
        # compatibility.
        stream.close
      end
    end

378
    # Turns the Response into a Rack-compatible array of the status, headers,
379
    # and body. Allows explicit splatting:
380 381
    #
    #   status, headers, body = *response
382
    def to_a
383
      commit!
384
      rack_response @status, @header.to_hash
385
    end
386
    alias prepare! to_a
387

388 389 390 391 392
    # Returns the response cookies, converted to a Hash of (name => value) pairs
    #
    #   assert_equal 'AuthorOfNewPage', r.cookies['author']
    def cookies
      cookies = {}
393
      if header = get_header(SET_COOKIE)
394 395
        header = header.split("\n") if header.respond_to?(:to_str)
        header.each do |cookie|
396
          if pair = cookie.split(";").first
397 398 399 400
            key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
            cookies[key] = value
          end
        end
401 402 403 404
      end
      cookies
    end

405
  private
J
Joshua Peek 已提交
406

A
Aaron Patterson 已提交
407
    ContentTypeHeader = Struct.new :mime_type, :charset
408
    NullContentTypeHeader = ContentTypeHeader.new nil, nil
A
Aaron Patterson 已提交
409

410
    def parse_content_type(content_type)
A
Aaron Patterson 已提交
411 412
      if content_type
        type, charset = content_type.split(/;\s*charset=/)
413
        type = nil if type && type.empty?
414
        ContentTypeHeader.new(type, charset)
A
Aaron Patterson 已提交
415
      else
416
        NullContentTypeHeader
A
Aaron Patterson 已提交
417 418 419
      end
    end

420 421 422 423 424 425
    # Small internal convenience method to get the parsed version of the current
    # content type header.
    def parsed_content_type_header
      parse_content_type(get_header(CONTENT_TYPE))
    end

A
Aaron Patterson 已提交
426
    def set_content_type(content_type, charset)
427
      type = (content_type || "").dup
428
      type << "; charset=#{charset.to_s.downcase}" if charset
A
Aaron Patterson 已提交
429 430 431
      set_header CONTENT_TYPE, type
    end

432
    def before_committed
433 434 435
      return if committed?
      assign_default_content_type_and_charset!
      handle_conditional_get!
436
      handle_no_content!
437 438 439
    end

    def before_sending
440 441 442 443 444 445 446
      # Normally we've already committed by now, but it's possible
      # (e.g., if the controller action tries to read back its own
      # response) to get here before that. In that case, we must force
      # an "early" commit: we're about to freeze the headers, so this is
      # our last chance.
      commit! unless committed?

E
eileencodes 已提交
447
      headers.freeze
448
      request.commit_cookie_jar! unless committed?
449 450
    end

451 452 453 454 455 456 457 458
    def build_buffer(response, body)
      Buffer.new response, body
    end

    def munge_body_object(body)
      body.respond_to?(:each) ? body : [body]
    end

459
    def assign_default_content_type_and_charset!
460
      return if content_type
J
Joshua Peek 已提交
461

462
      ct = parsed_content_type_header
463
      set_content_type(ct.mime_type || Mime[:html].to_s,
A
Aaron Patterson 已提交
464
                       ct.charset || self.class.default_charset)
465
    end
466

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    class RackBody
      def initialize(response)
        @response = response
      end

      def each(*args, &block)
        @response.each(*args, &block)
      end

      def close
        # Rack "close" maps to Response#abort, and *not* Response#close
        # (which is used when the controller's finished writing)
        @response.abort
      end

      def body
        @response.body
      end

      def respond_to?(method, include_private = false)
487
        if method.to_s == "to_path"
488 489 490 491 492 493 494 495 496
          @response.stream.respond_to?(method)
        else
          super
        end
      end

      def to_path
        @response.stream.to_path
      end
497 498 499 500

      def to_ary
        nil
      end
501 502
    end

503 504 505
    def handle_no_content!
      if NO_CONTENT_CODES.include?(@status)
        @header.delete CONTENT_TYPE
506
        @header.delete "Content-Length"
507 508 509
      end
    end

510
    def rack_response(status, header)
511
      if NO_CONTENT_CODES.include?(status)
512 513
        [status, header, []]
      else
514
        [status, header, RackBody.new(self)]
515 516
      end
    end
D
Initial  
David Heinemeier Hansson 已提交
517
  end
518
end