swift-server / async-http-client

HTTP client library built on SwiftNIO
https://swiftpackageindex.com/swift-server/async-http-client/main/documentation/asynchttpclient
Apache License 2.0
912 stars 117 forks source link

Two handy extensions to work with HTTPClientResponse body #736

Open makoni opened 6 months ago

makoni commented 6 months ago

Two extensions for HTTPClientResponse to avoid boilerplate code.

Reading a response data currently:

let expectedBytes = headers.first(name: "content-length").flatMap(Int.init) ?? 1024 * 1024
var bytes = try await body.collect(upTo: expectedBytes)
if let data = bytes.readData(length: bytes.readableBytes) {
    // handle data
}

With the extension:

if let data = try await response.data(upTo: 1024*1024) {
    // handle data
}

Additionally an extension for bytes. Currently:

let expectedBytes = headers.first(name: "content-length").flatMap(Int.init) ?? 1024 * 1024
var bytes = try await body.collect(upTo: expectedBytes)

With the extension:

var bytes = try await response.bytes(upTo: 1024*1024)