yello/hack-fetch

Hacklang 的简单 cURL 封装器

dev-main 2024-04-10 09:08 UTC

This package is auto-updated.

Last update: 2024-09-10 10:09:19 UTC


README

Hacklang 的简单 cURL 封装器。基本的 HTTP 客户端 API 受 node-fetch 启发。

安装

composer require yello/hack-fetch:dev-main

常见用法

纯文本或 HTML

use function Yello\HackFetch\fetch_async;

$response = await fetch_async('https://github.com/');
$body = await $response->textAsync();

echo $body;

JSON 响应

use function Yello\HackFetch\fetch_async;

$response = await fetch_async('https://api.github.com/users/github');
$data = await $response->jsonAsync();

echo $data;

简单的表单提交

use function Yello\HackFetch\fetch_async;

$response = await fetch_async(
  'https://httpbin.org/post',
  shape('method' => 'POST', 'body' => 'a=1'),
);
$data = await $response->jsonAsync();

echo $data;

使用 JSON 提交

use function Yello\HackFetch\fetch_async;

$response = await fetch_async(
  'https://httpbin.org/post',
  shape(
    'method' => 'POST',
    'body' => \json_encode(shape('a' => 1)),
    'headers' => dict['content-type' => 'application/json'],
  ),
);
$data = await $response->jsonAsync();

echo $data;

访问头部和其他元数据

use function Yello\HackFetch\fetch_async;

$response = await fetch_async('https://github.com/');

echo $response->ok() ? 'OK' : 'NOK';
echo $response->status();
echo $response->headers()['content-type'];

处理客户端和服务器错误

注意,3xx-5xx 的响应 不是 异常。

use function Yello\HackFetch\fetch_async;

$response = await fetch_async('https://httpbin.org/status/400');
if ($response->ok()) {
  // status >= 200 && status < 300
} else {
  echo $response->status(); // 400
}

处理异常

将 fetch 函数封装在 try/catch 块中可以捕获所有异常,包括来自核心库、网络错误和操作错误的错误。

use function Yello\HackFetch\fetch_async;

try {
  await fetch_async('https://domain.invalid');
} catch (\Exception $e) {
  echo $e->getMessage(); // Could not resolve host: domain.invalid
}

您可以使用异步迭代器来读取响应体。

use function Yello\HackFetch\fetch_async;

$response = 
  await fetch_async('https://httpbin.org/stream/3');

foreach ($response->body() await as $chunk) {
  echo $chunk;
}

文件下载

use function Yello\HackFetch\fetch_async;

$file = fopen($file_name, 'w');
$response = await fetch_async('https://httpbin.org/image/png');
foreach ($response->body() await as $chunk) {
  fwrite($file, $chunk);
}
fclose($file);

文件上传

use function Yello\HackFetch\fetch_async;

$file = fopen('test.png', 'r');
$response =
  await fetch_async('https://httpbin.org/anything', shape('file' => $file));
fclose($file);

echo $response->status();