-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
72-server-http-connect-proxy.php
56 lines (48 loc) · 1.85 KB
/
72-server-http-connect-proxy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
// $ php examples/72-server-http-connect-proxy.php 8080
// $ curl -v --proxy http://localhost:8080 https://reactphp.org/
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Message\Response;
use React\Socket\Connector;
use React\Socket\ConnectionInterface;
require __DIR__ . '/../vendor/autoload.php';
$connector = new Connector();
// Note how this example uses the `HttpServer` without the `StreamingRequestMiddleware`.
// Unlike the plain HTTP proxy, the CONNECT method does not contain a body
// and we establish an end-to-end connection over the stream object, so this
// doesn't have to store any payload data in memory at all.
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) use ($connector) {
if ($request->getMethod() !== 'CONNECT') {
return new Response(
Response::STATUS_METHOD_NOT_ALLOWED,
[
'Content-Type' => 'text/plain',
'Allow' => 'CONNECT'
],
'This is an HTTP CONNECT (secure HTTPS) proxy'
);
}
// try to connect to given target host
return $connector->connect($request->getRequestTarget())->then(
function (ConnectionInterface $remote) {
// connection established => forward data
return new Response(
Response::STATUS_OK,
[],
$remote
);
},
function (Exception $e) {
return new Response(
Response::STATUS_BAD_GATEWAY,
[
'Content-Type' => 'text/plain'
],
'Unable to connect: ' . $e->getMessage()
);
}
);
});
$socket = new React\Socket\SocketServer($argv[1] ?? '0.0.0.0:0');
$http->listen($socket);
echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;