定制 fangx/http-proxy 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

fangx/http-proxy

Composer 安装命令:

composer require fangx/http-proxy

包简介

http proxy.

关键字:

README 文档

README

Install

Via Composer

composer require fangx/http-proxy

Config

php bin/hyperf.php vendor:publish fangx/http-proxy

Or create config/autoload/http-proxy.php

<?php

// 默认的 headers / options / middlewares 都可以在每个 proxy 里单独配置
return [
    // 代理时, 默认保留的请求/响应头信息
    'headers' => [
        'request' => [
            'content-type',
            'user-agent',
            'authorization',
            'accept',
        ],
        'response' => [
            'content-type',
            'content-disposition',
        ],
    ],

    // 默认的 Guzzle 配置
    'options' => [
        'timeout' => 10,
    ],

    // 默认中间件
    'middlewares' => [
        // \Fangx\HttpProxy\Middleware\LoggerMiddleware::class
    ],

    // Proxy urls
    'proxy' => [
        'default' => [
            'url' => 'http://127.0.0.1:9502/open-api/',
        ],
        'other' => [
            'url' => 'http://127.0.0.1:9503/open-api/',
        ],
    ],
];

Usage

如下所示, 所有请求 /proxy/* 都会转发到 http://127.0.0.1:9502/open-api/*, 所有请求 /proxy-other/* 都会转发到 http://127.0.0.1:9503/open-api/*

路由

Router::addRoute(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH'], '/proxy/{uri:.*}', [IndexController::class, 'proxy']);
Router::addRoute(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH'], '/proxy-other/{uri:.*}', [IndexController::class, 'proxyOther']);

控制器

use Hyperf\HttpServer\Contract\RequestInterface;
use Fangx\HttpProxy\ProxyFactory;

class IndexController
{
    public function proxy(RequestInterface $request, ProxyFactory $factory)
    {
        return $factory->make()->proxy($request, $request->route('uri'));
    }

    public function proxyOther(RequestInterface $request, ProxyFactory $factory)
    {
        return $factory->make('other')->proxy($request, $request->route('uri'));
    }
}

Change Request

定义

use Fangx\HttpProxy\Contract\RequestMiddleware as ProxyMiddleware;
use Psr\Http\Message\RequestInterface;

class AddAuthorization extends ProxyMiddleware
{
    public function transfer(RequestInterface $request): RequestInterface
    {
        return $request->withHeader('authorization', 'Bearer 1234567890');
    }
}

使用

use Hyperf\HttpServer\Contract\RequestInterface;
use Fangx\HttpProxy\ProxyFactory;

class IndexController
{
    public function proxy(RequestInterface $request, ProxyFactory $factory)
    {
        return $factory->make()
                    ->withAddMiddleware(new AddAuthorization())
                    ->proxy($request, $request->route('uri'));
    }
}

Change Response

定义

use Fangx\HttpProxy\Contract\ResponseMiddleware as ProxyMiddleware;
use Psr\Http\Message\ResponseInterface;

class ConvertContentType extends ProxyMiddleware
{
    public function transfer(ResponseInterface $response): ResponseInterface
    {
        return $response->withHeader('content-type', 'text/html');
    }
}

使用

use Hyperf\HttpServer\Contract\RequestInterface;
use Fangx\HttpProxy\ProxyFactory;

class IndexController
{
    public function proxy(RequestInterface $request, ProxyFactory $factory)
    {
        return $factory->make()
                    ->withAddMiddleware(new ConvertContentType())
                    ->proxy($request, $request->route('uri'));
    }
}

直接定义 Middleware

\Fangx\HttpProxy\Middleware\LoggerMiddleware::class

use Fangx\HttpProxy\Contract\ProxyMiddleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Utils;
use Hyperf\Logger\LoggerFactory;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;

class LoggerMiddleware extends ProxyMiddleware
{
    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(ContainerInterface $container)
    {
        $this->logger = $container->get(LoggerFactory::class)->get('http-proxy');
    }

    public function __invoke(RequestInterface $request, array $options, callable $next)
    {
        if ($this->isUploadRequest($request)) {
            $body = 'upload files.';
        } else {
            $request = $this->setBodyParams($request, $data = $this->getBodyParams($request));
            $body = json_encode($data);
        }

        $this->logger->info('Proxy request: ' . $request->getUri()->getPath(), [
            'proxy_request_body' => $body,
        ]);

        /** @var PromiseInterface $promise */
        $promise = $next($request, $options);

        return $promise->then(function (ResponseInterface $response) {
            if ($this->isDownloadResponse($response)) {
                $body = 'download file.';
            } else {
                $response = $response->withBody(Utils::streamFor($body = $response->getBody()->getContents()));
            }

            $this->logger->info('Proxy response: ' . $response->getStatusCode(), [
                'proxy_response_body' => $body,
            ]);

            return $response;
        });
    }
}

Guzzle Exception

\GuzzleHttp\Exception;

  • GuzzleException
    • SeekException
    • InvalidArgumentException
    • TransferException
      • RequestException
        • TooManyRedirectsException
        • ConnectException
        • BadResponseException
          • ServerException
          • ClientException

fangx/http-proxy 适用场景与选型建议

fangx/http-proxy 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 9 次下载、GitHub Stars 达 3, 最近一次更新时间为 2020 年 11 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「hyperf」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 fangx/http-proxy 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 fangx/http-proxy 我们能提供哪些服务?
定制开发 / 二次开发

基于 fangx/http-proxy 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 9
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-11-17