|
6 | 6 | require_relative "body/streaming" |
7 | 7 | require_relative "body/enumerable" |
8 | 8 | require_relative "constants" |
| 9 | + |
9 | 10 | require "protocol/http/body/completable" |
| 11 | +require "protocol/http/body/head" |
10 | 12 |
|
11 | 13 | module Protocol |
12 | 14 | module Rack |
@@ -37,8 +39,9 @@ def self.no_content?(status) |
37 | 39 | # @parameter headers [Hash] The response headers. |
38 | 40 | # @parameter body [Object] The response body to wrap. |
39 | 41 | # @parameter input [Object] Optional input for streaming bodies. |
| 42 | + # @parameter head [Boolean] Indicates if this is a HEAD request, which should not have a body. |
40 | 43 | # @returns [Protocol::HTTP::Body] The wrapped response body. |
41 | | - def self.wrap(env, status, headers, body, input = nil) |
| 44 | + def self.wrap(env, status, headers, body, input = nil, head = false) |
42 | 45 | # In no circumstance do we want this header propagating out: |
43 | 46 | if length = headers.delete(CONTENT_LENGTH) |
44 | 47 | # We don't really trust the user to provide the right length to the transport. |
@@ -84,6 +87,19 @@ def self.wrap(env, status, headers, body, input = nil) |
84 | 87 | end |
85 | 88 | end |
86 | 89 |
|
| 90 | + # There are two main situations we need to handle: |
| 91 | + # 1. The application has the `Rack::Head` middleware in the stack, which means we should not return a body, and the application is also responsible for setting the content-length header. `Rack::Head` will result in an empty enumerable body. |
| 92 | + # 2. The application does not have `Rack::Head`, in which case it will return a body and we need to extract the length. |
| 93 | + # In both cases, we need to ensure that the body is wrapped correctly. If there is no body and we don't know the length, we also just return `nil`. |
| 94 | + if head |
| 95 | + if body |
| 96 | + body = ::Protocol::HTTP::Body::Head.for(body) |
| 97 | + elsif length |
| 98 | + body = ::Protocol::HTTP::Body::Head.new(length) |
| 99 | + end |
| 100 | + # Otherwise, body is `nil` and we don't know the length either. |
| 101 | + end |
| 102 | + |
87 | 103 | return body |
88 | 104 | end |
89 | 105 |
|
|
0 commit comments