Skip to content

Commit

Permalink
Update content-length header on setting response body (#425)
Browse files Browse the repository at this point in the history
* Update content-length header on setting response body

* Add createHeadResponse
  • Loading branch information
adam-fowler authored Apr 23, 2024
1 parent 32a724e commit 44e22bc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
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

0 comments on commit 44e22bc

Please sign in to comment.