jenssegers/proxy

一个代理库,将请求转发到指定的URL并返回响应。

v3.1.0 2020-03-06 09:32 UTC

This package is auto-updated.

Last update: 2024-09-05 14:03:47 UTC


README

Build Status Coverage Status

这是一个HTTP/HTTPS代理脚本,它将请求转发到不同的服务器并返回响应。Proxy类使用PSR7请求/响应对象作为输入/输出,并使用Guzzle来执行实际的HTTP请求。

安装

使用composer安装

composer require jenssegers/proxy

示例

以下示例创建了一个基于当前浏览器请求的请求对象,并将其转发到example.comRemoveEncodingFilter从原始响应中删除编码头,以便当前Web服务器可以正确设置这些。

use Proxy\Proxy;
use Proxy\Adapter\Guzzle\GuzzleAdapter;
use Proxy\Filter\RemoveEncodingFilter;
use Laminas\Diactoros\ServerRequestFactory;

// Create a PSR7 request based on the current browser request.
$request = ServerRequestFactory::fromGlobals();

// Create a guzzle client
$guzzle = new GuzzleHttp\Client();

// Create the proxy instance
$proxy = new Proxy(new GuzzleAdapter($guzzle));

// Add a response filter that removes the encoding headers.
$proxy->filter(new RemoveEncodingFilter());

try {
    // Forward the request and get the response.
    $response = $proxy->forward($request)->to('http://example.com');

    // Output response to the browser.
    (new Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($response);
} catch(\GuzzleHttp\Exception\BadResponseException $e) {
    // Correct way to handle bad responses
    (new Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($e->getResponse());
}

过滤器

您可以使用中间件策略对请求和响应应用过滤器。

$response = $proxy
	->forward($request)
	->filter(function ($request, $response, $next) {
		// Manipulate the request object.
		$request = $request->withHeader('User-Agent', 'FishBot/1.0');

		// Call the next item in the middleware.
		$response = $next($request, $response);

		// Manipulate the response object.
		$response = $response->withHeader('X-Proxy-Foo', 'Bar');

		return $response;
	})
	->to('http://example.com');