Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve body handling for HEAD responses #2310

Merged
merged 1 commit into from Apr 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 1 addition & 3 deletions Sources/Vapor/HTTP/Server/HTTPServerHandler.swift
Expand Up @@ -19,11 +19,9 @@ final class HTTPServerHandler: ChannelInboundHandler, RemovableChannelHandler {
case .failure(let error):
self.errorCaught(context: context, error: error)
case .success(let response):
let contentLength = response.headers.first(name: .contentLength)
if request.method == .HEAD {
response.body = .init()
response.forHeadRequest = true
}
response.headers.replaceOrAdd(name: .contentLength, value: contentLength ?? "0")
self.serialize(response, for: request, context: context)
}
}
Expand Down
5 changes: 3 additions & 2 deletions Sources/Vapor/HTTP/Server/HTTPServerResponseEncoder.swift
Expand Up @@ -31,8 +31,9 @@ final class HTTPServerResponseEncoder: ChannelOutboundHandler, RemovableChannelH
headers: response.headers
))), promise: nil)

if response.status == .noContent {
// don't send bodies for 204 (no content) requests
if response.status == .noContent || response.forHeadRequest {
// don't send bodies for 204 (no content) responses
// or HEAD requests
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: promise)
} else {
switch response.body.storage {
Expand Down
4 changes: 4 additions & 0 deletions Sources/Vapor/Response/Response.swift
Expand Up @@ -32,6 +32,9 @@ public final class Response: CustomStringConvertible {
didSet { self.headers.updateContentLength(self.body.count) }
}

// If `true`, don't serialize the body.
var forHeadRequest: Bool
Copy link
Sponsor Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Propose to rename to headOnlyRequest


internal enum Upgrader {
case webSocket(maxFrameSize: WebSocketMaxFrameSize, onUpgrade: (WebSocket) -> ())
}
Expand Down Expand Up @@ -134,6 +137,7 @@ public final class Response: CustomStringConvertible {
self.headers = headers
self.body = body
self.storage = .init()
self.forHeadRequest = false
}
}

Expand Down