PHPを追加する

This commit is contained in:
ry.yamafuji 2025-12-18 21:36:21 +09:00
parent 46b8cfddf4
commit ff6068afcd

74
src/bff/proxy.php Normal file
View File

@ -0,0 +1,74 @@
<?php
// =========================
// 設定
// =========================
$UPSTREAM_BASE_URL = getenv('UPSTREAM_BASE_URL');
// 例: https://xxxxx-uc.a.run.app
if (!$UPSTREAM_BASE_URL) {
http_response_code(500);
echo 'UPSTREAM_BASE_URL is not set';
exit;
}
// =========================
// リクエスト情報
// =========================
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI']; // パス + クエリ
// 転送先URL
$targetUrl = rtrim($UPSTREAM_BASE_URL, '/') . $uri;
// =========================
// ヘッダ取得
// =========================
$headers = [];
foreach (getallheaders() as $k => $v) {
if (strtolower($k) === 'host') continue;
$headers[] = "$k: $v";
}
// =========================
// body非ストリーミング
// =========================
$body = null;
if (!in_array($method, ['GET', 'HEAD'])) {
$body = file_get_contents('php://input');
}
// =========================
// 中継実行
// =========================
$context = stream_context_create([
'http' => [
'method' => $method,
'header' => implode("\r\n", $headers),
'content' => $body,
'ignore_errors' => true, // 4xx / 5xx も取得
]
]);
$responseBody = file_get_contents($targetUrl, false, $context);
// =========================
// ステータスコード
// =========================
if (isset($http_response_header[0])) {
if (preg_match('#HTTP/\d\.\d\s+(\d+)#', $http_response_header[0], $m)) {
http_response_code((int)$m[1]);
}
}
// =========================
// レスポンスヘッダ
// =========================
foreach ($http_response_header as $h) {
if (stripos($h, 'Transfer-Encoding:') === 0) continue;
if (stripos($h, 'Connection:') === 0) continue;
header($h, false);
}
// =========================
// レスポンスボディ
// =========================
echo $responseBody;