|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the AsyncHTTPClient open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2022 Apple Inc. and the AsyncHTTPClient project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +// TODO: remove @testable after async/await API is public |
| 16 | +@testable import AsyncHTTPClient |
| 17 | +import NIOCore |
| 18 | + |
| 19 | +#if compiler(>=5.5.2) && canImport(_Concurrency) |
| 20 | + |
| 21 | +@main |
| 22 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 23 | +struct StreamingByteCounter { |
| 24 | + static func main() async throws { |
| 25 | + let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) |
| 26 | + do { |
| 27 | + let request = HTTPClientRequest(url: "https://apple.com") |
| 28 | + let response = try await httpClient.execute(request, timeout: .seconds(30)) |
| 29 | + print("HTTP head", response) |
| 30 | + |
| 31 | + // if defined, the content-length headers announces the size of the body |
| 32 | + let expectedBytes = response.headers.first(name: "content-length").flatMap(Int.init) |
| 33 | + |
| 34 | + var receivedBytes = 0 |
| 35 | + // asynchronously iterates over all body fragments |
| 36 | + // this loop will automatically propagate backpressure correctly |
| 37 | + for try await buffer in response.body { |
| 38 | + // For this example, we are just interested in the size of the fragment |
| 39 | + receivedBytes += buffer.readableBytes |
| 40 | + |
| 41 | + if let expectedBytes = expectedBytes { |
| 42 | + // if the body size is known, we calculate a progress indicator |
| 43 | + let progress = Double(receivedBytes)/Double(expectedBytes) |
| 44 | + print("progress: \(Int(progress * 100))%") |
| 45 | + } |
| 46 | + // in case backpressure is needed, all reads will be paused until returned future is resolved |
| 47 | + } |
| 48 | + print("did receive \(receivedBytes) bytes") |
| 49 | + } catch { |
| 50 | + print("request failed:", error) |
| 51 | + } |
| 52 | + // it is important to shutdown the httpClient after all requests are done, even if one failed |
| 53 | + try await httpClient.shutdown() |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +#endif |
0 commit comments