123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- declare(strict_types=1);
- namespace App\Master\Framework\Library;
- use GuzzleHttp\Client;
- use GuzzleHttp\RequestOptions;
- use Hyperf\Guzzle\HandlerStackFactory;
- /**
- * 扩展返回工具
- */
- class Library
- {
- protected string $base_uri = 'http://127.0.0.1:9501';
- protected string $message = 'error';
- protected mixed $data = [];
- /**
- * post json 请求
- *
- * @param string $uri
- * @param array $params
- * @param array $header
- * @return \Psr\Http\Message\ResponseInterface
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- protected function postJson(string $uri, array $params = [], array $header = [])
- {
- $factory = new HandlerStackFactory();
- $stack = $factory->create();
- $client = new Client([
- // guzzle http里的配置信息
- 'base_uri' => $this->base_uri,
- 'handler' => $stack,
- 'timeout' => 5,
- // swoole的配置信息,内容会覆盖guzzle http里的配置信息
- 'swoole' => [
- 'timeout' => 10,
- 'socket_buffer_size' => 1024 * 1024 * 2,
- ],
- ]);
- return $client->post($uri, [
- RequestOptions::JSON => $params,
- RequestOptions::VERIFY => false,
- RequestOptions::HEADERS => array_merge(
- $header,
- [
- 'Content-Type' => 'application/json'
- ]
- ),
- ]);
- }
- /**
- * 返回成功结果
- * @param string $message
- * @param mixed $data
- * @return bool
- */
- protected function success(string $message = 'success', mixed $data = []): bool
- {
- $this->message = $message;
- $this->data = $data;
- return true;
- }
- /**
- * 返回失败结果
- * @param string $message
- * @param mixed $data
- * @return bool
- */
- protected function error(string $message = 'error', mixed $data = []): bool
- {
- $this->message = $message;
- $this->data = $data;
- return false;
- }
- /**
- * 获取成功数据
- * @return mixed
- */
- public function getData(): mixed
- {
- return $this->data;
- }
- /**
- * 获取消息
- * @return string
- */
- public function getMessage(): string
- {
- return $this->message;
- }
- }
|