Skip to content

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

Merged
merged 6 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions Examples/GetHTML/GetHTML.swift
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)
Copy link
Member

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?


@main
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
Copy link
Member

Choose a reason for hiding this comment

The 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
56 changes: 56 additions & 0 deletions Examples/GetJSON/GetJSON.swift
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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe add a comment here that this function is an overload from NIOFoundationCompat.

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
58 changes: 58 additions & 0 deletions Examples/Package.swift
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"
),
]
)
11 changes: 11 additions & 0 deletions Examples/README.md
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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be good to enumerate what each example demonstrates.


57 changes: 57 additions & 0 deletions Examples/StreamingByteCounter/StreamingByteCounter.swift
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
7 changes: 7 additions & 0 deletions Sources/AsyncHTTPClient/AsyncAwait/HTTPClientResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ public struct HTTPClientResponse {
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension HTTPClientResponse: CustomStringConvertible {
public var description: String {
return "HTTPClientResponse(version: \(self.version), status: \(self.status), headers: \(self.headers))"
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension HTTPClientResponse.Body: AsyncSequence {
public typealias Element = AsyncIterator.Element
Expand Down