Skip to content

Commit d82ff28

Browse files
committed
update README.md for async/await
1 parent f3830d1 commit d82ff28

File tree

1 file changed

+78
-7
lines changed

1 file changed

+78
-7
lines changed

README.md

+78-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
This package provides simple HTTP Client library built on top of SwiftNIO.
33

44
This library provides the following:
5+
- First class support for Swift Concurrency (since version 1.9.0)
56
- Asynchronous and non-blocking request methods
67
- Simple follow-redirects (cookie headers are dropped)
78
- Streaming body download
@@ -11,7 +12,7 @@ This library provides the following:
1112

1213
---
1314

14-
**NOTE**: You will need [Xcode 11.4](https://apps.apple.com/gb/app/xcode/id497799835?mt=12) or [Swift 5.2](https://swift.org/download/#swift-52) to try out `AsyncHTTPClient`.
15+
**NOTE**: You will need [Xcode 13.2](https://apps.apple.com/gb/app/xcode/id497799835?mt=12) or [Swift 5.5.2](https://swift.org/download/#swift-552) to try out `AsyncHTTPClient`s new async/await APIs.
1516

1617
---
1718

@@ -21,7 +22,7 @@ This library provides the following:
2122
Add the following entry in your <code>Package.swift</code> to start using <code>HTTPClient</code>:
2223

2324
```swift
24-
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.0.0")
25+
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.9.0")
2526
```
2627
and `AsyncHTTPClient` dependency to your target:
2728
```swift
@@ -40,7 +41,21 @@ If your application does not use SwiftNIO yet, it is acceptable to use `eventLoo
4041
import AsyncHTTPClient
4142

4243
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
43-
httpClient.get(url: "https://swift.org").whenComplete { result in
44+
45+
/// MARK: - Using Swift Concurrency
46+
let request = HTTPClientRequest(url: "https://apple.com/")
47+
let response = try await httpClient.execute(request, timeout: .seconds(30))
48+
print("HTTP head", response)
49+
if response.status == .ok {
50+
let body = try await response.body.collect(upTo: 1024 * 1024) // 1 MB
51+
// handle body
52+
} else {
53+
// handle remote error
54+
}
55+
56+
57+
/// MARK: - Using SwiftNIO EventLoopFuture
58+
httpClient.get(url: "https://apple.com/").whenComplete { result in
4459
switch result {
4560
case .failure(let error):
4661
// process error
@@ -58,7 +73,32 @@ You should always shut down `HTTPClient` instances you created using `try httpCl
5873

5974
## Usage guide
6075

61-
Most common HTTP methods are supported out of the box. In case you need to have more control over the method, or you want to add headers or body, use the `HTTPRequest` struct:
76+
The default HTTP Method is `GET`. In case you need to have more control over the method, or you want to add headers or body, use the `HTTPClientRequest` struct:
77+
#### Using Swift Concurrency
78+
```swift
79+
import AsyncHTTPClient
80+
81+
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
82+
do {
83+
var request = HTTPClientRequest(url: "https://apple.com/")
84+
request.method = .POST
85+
request.headers.add(name: "User-Agent", value: "Swift HTTPClient")
86+
request.body = .bytes(ByteBuffer(string: "some data"))
87+
88+
let response = try await httpClient.execute(request, timeout: .seconds(30))
89+
if response.status == .ok {
90+
// handle response
91+
} else {
92+
// handle remote error
93+
}
94+
} catch {
95+
// handle error
96+
}
97+
// it's important to shutdown the httpClient after all requests are done, even if one failed
98+
try await httpClient.shutdown()
99+
```
100+
101+
#### Using SwiftNIO EventLoopFuture
62102
```swift
63103
import AsyncHTTPClient
64104

@@ -67,7 +107,7 @@ defer {
67107
try? httpClient.syncShutdown()
68108
}
69109

70-
var request = try HTTPClient.Request(url: "https://swift.org", method: .POST)
110+
var request = try HTTPClient.Request(url: "https://apple.com/", method: .POST)
71111
request.headers.add(name: "User-Agent", value: "Swift HTTPClient")
72112
request.body = .string("some-body")
73113

@@ -105,7 +145,38 @@ httpClient.execute(request: request, deadline: .now() + .milliseconds(1))
105145
```
106146

107147
### Streaming
108-
When dealing with larger amount of data, it's critical to stream the response body instead of aggregating in-memory. Handling a response stream is done using a delegate protocol. The following example demonstrates how to count the number of bytes in a streaming response body:
148+
When dealing with larger amount of data, it's critical to stream the response body instead of aggregating in-memory.
149+
The following example demonstrates how to count the number of bytes in a streaming response body:
150+
151+
#### Using Swift Concurrency
152+
```swift
153+
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
154+
155+
let request = HTTPClientRequest(url: "https://apple.com/")
156+
let response = try await httpClient.execute(request, timeout: .seconds(30))
157+
print("HTTP head", response)
158+
159+
// if defined, the content-length headers announces the size of the body
160+
let expectedBytes = response.headers.first(name: "content-length").flatMap(Int.init)
161+
162+
var receivedBytes = 0
163+
// asynchronously iterates over all body fragments.
164+
for try await buffer in response.body {
165+
// For this example, we are just interested in the size of the fragment
166+
receivedBytes += buffer.readableBytes
167+
168+
if let expectedBytes = expectedBytes {
169+
// if the body size is known, we calculate a progress indicator
170+
let progress = Double(receivedBytes)/Double(expectedBytes)
171+
print("progress: \(Int(progress * 100))%")
172+
}
173+
// in case backpressure is needed, all reads will be paused until the end of the for loop.
174+
}
175+
print("did receive \(receivedBytes) bytes")
176+
```
177+
178+
#### Using HTTPClientResponseDelegate and SwiftNIO EventLoopFuture
179+
109180
```swift
110181
import NIOCore
111182
import NIOHTTP1
@@ -158,7 +229,7 @@ class CountingDelegate: HTTPClientResponseDelegate {
158229
}
159230
}
160231

161-
let request = try HTTPClient.Request(url: "https://swift.org")
232+
let request = try HTTPClient.Request(url: "https://apple.com/")
162233
let delegate = CountingDelegate()
163234

164235
httpClient.execute(request: request, delegate: delegate).futureResult.whenSuccess { count in

0 commit comments

Comments
 (0)