torres-developer / reverse-proxy
仅使用PHP的Reverse Proxy
dev-master
2023-04-23 00:29 UTC
Requires
- psr/http-client: ^1.0
- torres-developer/pull: dev-master
Requires (Dev)
- pds/skeleton: ^1.0
Provides
This package is auto-updated.
Last update: 2024-08-23 03:25:29 UTC
README
一个使用PHP的Reverse Proxy。
为什么?
我的学校为学生提供了一个服务器。
我们可以提供静态文件,同时PHP也得到了支持。这就是为什么它是用PHP编写的。
假设我在localhost端口3000创建了一个HTTP服务器(使用PHP、node.js等)。我无法让人们能够通过互联网访问它,因为我没有权限更改Apache服务器配置或创建反向代理。
我正在尝试使用我得到的工具:)
示例
最简单的用法
它将始终反向代理到http://localhost:3000/
。
<?php declare(encoding="UTF-8"); declare(strict_types=1); use function TorresDeveloper\ReverseProxy\reverse_proxy; require __DIR__ . "/vendor/autoload.php"; reverse_proxy("http://localhost:3000/");
另一个示例
在这个示例中,与另一个示例相反,请求不总是发送到http://localhost:3000/
。您需要向路径/app/
发送请求,然后出现在/app/
之后的内容也将是反向代理请求的请求路径的一部分,因此对/app/something/
的请求将执行对http://localhost:3000/something/
的请求。
我还展示了如何处理一些\Exception
,以及如何使用respond
函数来向客户端显示状态码、头和正文。
<?php declare(encoding="UTF-8"); declare(strict_types=1); use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\NetworkExceptionInterface; use Psr\Http\Client\RequestExceptionInterface; use TorresDeveloper\HTTPMessage\Response; use TorresDeveloper\HTTPMessage\URI; use TorresDeveloper\ReverseProxy\ReverseProxy; use function TorresDeveloper\ReverseProxy\respond; use function TorresDeveloper\ReverseProxy\serverRequest; require __DIR__ . "/vendor/autoload.php"; $proxy = new ReverseProxy("/app/", new URI("http://localhost:3000/")); try { $res = $proxy->sendRequest(serverRequest()); } catch (RequestExceptionInterface $e) { $method = $e->getRequest()->getMethod(); $uri = $e->getRequest()->getUri(); respond(new Response( 500, body: "Request `[$method] $uri` failed.", headers: [ "Content-Type" => "text/plain" ] )); } catch (NetworkExceptionInterface $e) { $method = $e->getRequest()->getMethod(); $uri = $e->getRequest()->getUri(); respond(new Response( 500, body: "Request `[$method] $uri` could not be completed because of network issues.", headers: [ "Content-Type" => "text/plain" ] )); } catch (ClientExceptionInterface $e) { respond(new Response( 500, body: "Unexpected error occured on the reverse proxy side.", headers: [ "Content-Type" => "text/plain" ] )); } catch (\Throwable $th) { respond(new Response( 500, body: "Unexpected error occured.", headers: [ "Content-Type" => "text/plain" ] )); } if ($res->getStatusCode() === 404) { // It might be that the request to possibly reverse proxy didn't start with // the path of the endpoint defined on the ReverseProxy::__constructor // earlier in the code. } respond($res); exit(0);