-
Notifications
You must be signed in to change notification settings - Fork 125
Add async/await examples #553
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
Changes from 2 commits
7a71e83
755012b
f0832bb
b55bf11
44e6fd4
be99b35
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the AsyncHTTPClient open source project | ||
// | ||
// Copyright (c) 2022 Apple Inc. and the AsyncHTTPClient project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
// TODO: remove @testable after async/await API is public | ||
@testable import AsyncHTTPClient | ||
import NIOCore | ||
|
||
#if compiler(>=5.5.2) && canImport(_Concurrency) | ||
|
||
@main | ||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we should put those platform requirements in package itself. |
||
struct GetHTML { | ||
static func main() async throws { | ||
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) | ||
do { | ||
let request = HTTPClientRequest(url: "https://apple.com") | ||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
print("HTTP head", response) | ||
let body = try await response.body.collect(upTo: 1024 * 1024) // 1 MB | ||
print(String(buffer: body)) | ||
} catch { | ||
print("request failed:", error) | ||
} | ||
// it is important to shutdown the httpClient after all requests are done, even if one failed | ||
try await httpClient.shutdown() | ||
} | ||
} | ||
|
||
#endif |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the AsyncHTTPClient open source project | ||
// | ||
// Copyright (c) 2022 Apple Inc. and the AsyncHTTPClient project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
// TODO: remove @testable after async/await API is public | ||
@testable import AsyncHTTPClient | ||
import Foundation | ||
import NIOCore | ||
import NIOFoundationCompat | ||
|
||
#if compiler(>=5.5.2) && canImport(_Concurrency) | ||
|
||
struct Comic: Codable { | ||
var num: Int | ||
var title: String | ||
var day: String | ||
var month: String | ||
var year: String | ||
var img: String | ||
var alt: String | ||
var news: String | ||
var link: String | ||
var transcript: String | ||
} | ||
|
||
@main | ||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) | ||
struct GetJSON { | ||
static func main() async throws { | ||
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) | ||
do { | ||
let request = HTTPClientRequest(url: "https://xkcd.com/info.0.json") | ||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
print("HTTP head", response) | ||
let body = try await response.body.collect(upTo: 1024 * 1024) // 1 MB | ||
let comic = try JSONDecoder().decode(Comic.self, from: body) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. maybe add a comment here that this function is an overload from |
||
dump(comic) | ||
} catch { | ||
print("request failed:", error) | ||
} | ||
// it is important to shutdown the httpClient after all requests are done, even if one failed | ||
try await httpClient.shutdown() | ||
} | ||
} | ||
|
||
#endif |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// swift-tools-version:5.5 | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the AsyncHTTPClient open source project | ||
// | ||
// Copyright (c) 2018-2022 Apple Inc. and the AsyncHTTPClient project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import PackageDescription | ||
|
||
let package = Package( | ||
name: "async-http-client-examples", | ||
products: [ | ||
.executable(name: "GetHTML", targets: ["GetHTML"]), | ||
.executable(name: "GetJSON", targets: ["GetJSON"]), | ||
.executable(name: "StreamingByteCounter", targets: ["StreamingByteCounter"]), | ||
], | ||
dependencies: [ | ||
.package(url: "https://github.com/apple/swift-nio.git", .branch("main")), | ||
|
||
// in real-world projects this would be | ||
// .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.9.0") | ||
.package(name: "async-http-client", path: "../"), | ||
], | ||
targets: [ | ||
// MARK: - Examples | ||
|
||
.executableTarget( | ||
name: "GetHTML", | ||
dependencies: [ | ||
.product(name: "AsyncHTTPClient", package: "async-http-client"), | ||
.product(name: "NIOCore", package: "swift-nio"), | ||
], path: "GetHTML" | ||
), | ||
.executableTarget( | ||
name: "GetJSON", | ||
dependencies: [ | ||
.product(name: "AsyncHTTPClient", package: "async-http-client"), | ||
.product(name: "NIOCore", package: "swift-nio"), | ||
.product(name: "NIOFoundationCompat", package: "swift-nio"), | ||
], path: "GetJSON" | ||
), | ||
.executableTarget( | ||
name: "StreamingByteCounter", | ||
dependencies: [ | ||
.product(name: "AsyncHTTPClient", package: "async-http-client"), | ||
.product(name: "NIOCore", package: "swift-nio"), | ||
], path: "StreamingByteCounter" | ||
), | ||
] | ||
) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
# Examples | ||
This folder includes a couple of Examples for `AsyncHTTPClient`. | ||
You can run them by opening the `Package.swift` in this folder through Xcode. | ||
In Xcode you can then select the scheme for the example you want run e.g. `GetHTML`. | ||
|
||
You can also run the examples from the command line by executing the follow command in this folder: | ||
``` | ||
swift run GetHTML | ||
``` | ||
To run other examples you can just replace `GetHTML` with the name of the example you want to run. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it would be good to enumerate what each example demonstrates. |
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the AsyncHTTPClient open source project | ||
// | ||
// Copyright (c) 2022 Apple Inc. and the AsyncHTTPClient project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
// TODO: remove @testable after async/await API is public | ||
@testable import AsyncHTTPClient | ||
import NIOCore | ||
|
||
#if compiler(>=5.5.2) && canImport(_Concurrency) | ||
|
||
@main | ||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) | ||
struct StreamingByteCounter { | ||
static func main() async throws { | ||
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) | ||
do { | ||
let request = HTTPClientRequest(url: "https://apple.com") | ||
let response = try await httpClient.execute(request, timeout: .seconds(30)) | ||
print("HTTP head", response) | ||
|
||
// if defined, the content-length headers announces the size of the body | ||
let expectedBytes = response.headers.first(name: "content-length").flatMap(Int.init) | ||
|
||
var receivedBytes = 0 | ||
// asynchronously iterates over all body fragments | ||
// this loop will automatically propagate backpressure correctly | ||
for try await buffer in response.body { | ||
// For this example, we are just interested in the size of the fragment | ||
receivedBytes += buffer.readableBytes | ||
|
||
if let expectedBytes = expectedBytes { | ||
// if the body size is known, we calculate a progress indicator | ||
let progress = Double(receivedBytes) / Double(expectedBytes) | ||
print("progress: \(Int(progress * 100))%") | ||
} | ||
// in case backpressure is needed, all reads will be paused until returned future is resolved | ||
} | ||
print("did receive \(receivedBytes) bytes") | ||
} catch { | ||
print("request failed:", error) | ||
} | ||
// it is important to shutdown the httpClient after all requests are done, even if one failed | ||
try await httpClient.shutdown() | ||
} | ||
} | ||
|
||
#endif |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we put the examples into an extra package, can we drop those?