forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path71-server-http-proxy.php
56 lines (46 loc) · 1.95 KB
/
71-server-http-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/71-server-http-proxy.php 8080
// $ curl -v --proxy http://localhost:8080 http://reactphp.org/
use Psr\Http\Message\RequestInterface;
use React\EventLoop\Factory;
use React\Http\Message\Response;
use React\Http\Server;
use RingCentral\Psr7;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
// Note how this example uses the `Server` without the `StreamingRequestMiddleware`.
// This means that this proxy buffers the whole request before "processing" it.
// As such, this is store-and-forward proxy. This could also use the advanced
// `StreamingRequestMiddleware` to forward the incoming request as it comes in.
$server = new Server($loop, function (RequestInterface $request) {
if (strpos($request->getRequestTarget(), '://') === false) {
return new Response(
400,
array(
'Content-Type' => 'text/plain'
),
'This is a plain HTTP proxy'
);
}
// prepare outgoing client request by updating request-target and Host header
$host = (string)$request->getUri()->withScheme('')->withPath('')->withQuery('');
$target = (string)$request->getUri()->withScheme('')->withHost('')->withPort(null);
if ($target === '') {
$target = $request->getMethod() === 'OPTIONS' ? '*' : '/';
}
$outgoing = $request->withRequestTarget($target)->withHeader('Host', $host);
// pseudo code only: simply dump the outgoing request as a string
// left up as an exercise: use an HTTP client to send the outgoing request
// and forward the incoming response to the original client request
return new Response(
200,
array(
'Content-Type' => 'text/plain'
),
Psr7\str($outgoing)
);
});
$socket = new \React\Socket\Server(isset($argv[1]) ? $argv[1] : '0.0.0.0:0', $loop);
$server->listen($socket);
echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;
$loop->run();