Skip to content

Large Requests with HTTPBodySequence

Compare
Choose a tag to compare
@swhitty swhitty released this 03 Apr 00:22
· 214 commits to main since this release
96d7101

Adds support for very large bodies within HTTPRequest and HTTPResponse that can be processed in Data chunks.

HTTPRequest

Requests now include a bodySequence: HTTPBodySequence which allows the request body to be iterated in small chunks as the arrive:

func saveBody(request: HTTPRequest) async throws -> HTTPResponse {
  let file = URL(fileURLWithPath: "/tmp/file")
  _ = FileManager.default.createFile(atPath: file.path, contents: nil)
  let handle = try FileHandle(forWritingTo: file)
  for try await chunk in req.bodySequence {
    try handle.write(contentsOf: chunk)
  }
  return HTTPResponse(statusCode: .ok)
}

The existing var data: Data property has been deprecated, but is still supported and synchronously returns the uploaded data for requests less than 10 MiB.

HTTPResponse

Response payloads can provide a HTTPBodySequence which allows the response body to be provided in small chunks as they are sent:

func getXcode(request: HTTPRequest) async throws -> HTTPResponse {
  try HTTPResponse(
    statusCode: .ok,
    body: HTTPBodySequence(file: URL(fileURLWithPath: "/tmp/Xcode_14.3.xip"))
  )
}

Providing a Data instance for the body property is still supported.

The existing var data: Data? property has been deprecated, but is still supported and synchronously returns response payload if the response is not a web socket or HTTPBodySequence.

FileHTTPHandler

The existing FileHTTPHandler now serves all files larger than 10 MiB in small chunks, while files smaller are still served via a complete Data instance.