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

Update content-length header on setting response body #425

Merged
merged 2 commits into from
Apr 23, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions Sources/Hummingbird/Router/EndpointResponder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,8 @@ struct EndpointResponders<Context: BaseRequestContext>: Sendable {
mutating func autoGenerateHeadEndpoint() {
if self.methods[.head] == nil, let get = methods[.get] {
self.methods[.head] = CallbackResponder { request, context in
var response = try await get.respond(to: request, context: context)
response.body = .init()
return response
let response = try await get.respond(to: request, context: context)
return response.createHeadResponse()
}
}
}
Expand Down
13 changes: 12 additions & 1 deletion Sources/HummingbirdCore/Response/Response.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ import HTTPTypes
/// Holds all the required to generate a HTTP Response
public struct Response: Sendable {
public var head: HTTPResponse
public var body: ResponseBody
public var body: ResponseBody {
didSet {
if let contentLength = body.contentLength {
self.head.headerFields[.contentLength] = String(describing: contentLength)
}
}
}

public init(status: HTTPResponse.Status, headers: HTTPFields = .init(), body: ResponseBody = .init()) {
self.head = .init(status: status, headerFields: headers)
Expand All @@ -36,6 +42,11 @@ public struct Response: Sendable {
get { self.head.headerFields }
set { self.head.headerFields = newValue }
}

/// Return HEAD response based off this response
public func createHeadResponse() -> Response {
.init(status: self.status, headers: self.headers, body: .init())
}
}

extension Response: CustomStringConvertible {
Expand Down
Loading