forked from amphp/http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-concurrent-fetch.php
45 lines (35 loc) · 1.25 KB
/
1-concurrent-fetch.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Amp\Loop;
require __DIR__ . '/../.helper/functions.php';
Loop::run(static function () use ($argv): \Generator {
$uris = [
"https://google.com/",
"https://github.com/",
"https://stackoverflow.com/",
];
// Instantiate the HTTP client
$client = HttpClientBuilder::buildDefault();
$requestHandler = static function (string $uri) use ($client): \Generator {
/** @var Response $response */
$response = yield $client->request(new Request($uri));
return yield $response->getBody()->buffer();
};
try {
$promises = [];
foreach ($uris as $uri) {
$promises[$uri] = Amp\call($requestHandler, $uri);
}
$bodies = yield $promises;
foreach ($bodies as $uri => $body) {
print $uri . " - " . \strlen($body) . " bytes" . PHP_EOL;
}
} catch (HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The HttpClient::request() method itself will never throw directly, but returns a promise.
echo $error;
}
});