Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 59 lines (47 sloc) 1.359 kb
1270a6d @rtomayko Add Rack::Chunked (Transfer-Encoding: chunked) middleware
rtomayko authored
1 require 'rack/utils'
2
3 module Rack
4
5 # Middleware that applies chunked transfer encoding to response bodies
6 # when the response does not include a Content-Length header.
7 class Chunked
8 include Rack::Utils
9
4d93f90 @tenderlove use a chunked body wrapper rather than duping and returning the chunked ...
tenderlove authored
10 # A body wrapper that emits chunked responses
11 class Body
12 TERM = "\r\n"
13 TAIL = "0#{TERM}#{TERM}"
14
15 include Rack::Utils
16
17 def initialize(body)
18 @body = body
19 end
20
21 def each
22 term = TERM
23 @body.each do |chunk|
24 size = bytesize(chunk)
25 next if size == 0
a81e9e1 @dim Ensure correct encoding on chunked responses
dim authored
26
27 chunk = chunk.dup.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding)
4d93f90 @tenderlove use a chunked body wrapper rather than duping and returning the chunked ...
tenderlove authored
28 yield [size.to_s(16), term, chunk, term].join
29 end
30 yield TAIL
31 end
32
33 def close
34 @body.close if @body.respond_to?(:close)
35 end
36 end
3a449f6 @raggi minor performance items on rack::chunked
raggi authored
37
1270a6d @rtomayko Add Rack::Chunked (Transfer-Encoding: chunked) middleware
rtomayko authored
38 def initialize(app)
39 @app = app
40 end
41
42 def call(env)
43 status, headers, body = @app.call(env)
44 headers = HeaderHash.new(headers)
45
46 if env['HTTP_VERSION'] == 'HTTP/1.0' ||
47 STATUS_WITH_NO_ENTITY_BODY.include?(status) ||
48 headers['Content-Length'] ||
49 headers['Transfer-Encoding']
8f836f4 avoid HeaderHash#to_hash in middlewares
Eric Wong authored
50 [status, headers, body]
1270a6d @rtomayko Add Rack::Chunked (Transfer-Encoding: chunked) middleware
rtomayko authored
51 else
4d93f90 @tenderlove use a chunked body wrapper rather than duping and returning the chunked ...
tenderlove authored
52 headers.delete('Content-Length')
53 headers['Transfer-Encoding'] = 'chunked'
54 [status, headers, Body.new(body)]
1270a6d @rtomayko Add Rack::Chunked (Transfer-Encoding: chunked) middleware
rtomayko authored
55 end
56 end
57 end
58 end
Something went wrong with that request. Please try again.