diff --git a/examples/behind-proxy.php b/examples/behind-proxy.php new file mode 100644 index 00000000..c1325a99 --- /dev/null +++ b/examples/behind-proxy.php @@ -0,0 +1,58 @@ +#!/usr/bin/env php +pushProcessor(new PsrLogMessageProcessor()); +$logHandler->setFormatter(new ConsoleFormatter()); +$logger = new Logger('server'); +$logger->pushHandler($logHandler); +$logger->useLoggingLoopDetection(false); + +$server = SocketHttpServer::createForBehindProxy( + logger: $logger, + headerType: ForwardedHeaderType::XForwardedFor, + trustedProxies: ["172.18.0.0/24"], +); + +$server->expose("0.0.0.0:8080"); + +$server->start(new class implements RequestHandler { + public function handleRequest(Request $request): Response + { + /** @var Forwarded|null $forwarded */ + $forwarded = $request->getAttribute(Forwarded::class); + $for = $forwarded?->getFor() ?? $request->getClient()->getRemoteAddress(); + + return new Response( + status: HttpStatus::OK, + headers: ["content-type" => "text/plain; charset=utf-8"], + body: "Hello, " . $for->toString(), + ); + } +}, new DefaultErrorHandler()); + +// Await a termination signal to be received. +$signal = trapSignal([\SIGHUP, \SIGINT, \SIGQUIT, \SIGTERM]); + +$logger->info(sprintf("Received signal %d, stopping HTTP server", $signal)); + +$server->stop();