Created
March 27, 2025 00:42
-
-
Save felipsmartins/7b67a11be71bba839b422af39305a70c to your computer and use it in GitHub Desktop.
php echo server (with gzip support)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// php -S 127.1:8090 -t . | |
function log_request(array $body = []) | |
{ | |
// guess body | |
if (count($body) === 0) { | |
if ($_POST) { | |
$body = $_POST; | |
} | |
$json = file_get_contents("php://input"); | |
$json = json_decode($json, true); | |
if ($json) { | |
$body = $json; | |
} | |
} | |
$headers = getallheaders(); | |
$http_method = $_SERVER["REQUEST_METHOD"]; | |
$request_uri = $_SERVER["REQUEST_URI"]; | |
$now = date("Y-m-d H:i:s"); | |
$lines = join("\n\n", [ | |
sprintf("[%s] %s %s", $now, $http_method, $request_uri), | |
json_encode($headers, JSON_PRETTY_PRINT), | |
json_encode($body, JSON_PRETTY_PRINT), | |
"----------------------------------------------------------------------\n\n", | |
]); | |
file_put_contents("/tmp/x-request-log.text", $lines, FILE_APPEND); | |
} | |
function has_compressed_request_body() | |
{ | |
// expected header when compressed: "Content-Encoding": "gzip", | |
return array_key_exists("Content-Encoding", getallheaders()) && | |
getallheaders()["Content-Encoding"]; | |
} | |
function get_request_body() | |
{ | |
if (has_compressed_request_body()) { | |
return gzdecode(file_get_contents("php://input")); | |
} | |
return file_get_contents("php://input"); | |
} | |
function buildBigQResponseOk(array $messages) | |
{ | |
$results = []; | |
foreach ($messages as $message) { | |
array_push($results, [ | |
"data" => $message["msg"], | |
"status_code" => 500, | |
]); | |
} | |
return [ | |
"status_code" => 207, | |
"results" => $results, | |
]; | |
} | |
// Boostraping | |
// =============== | |
$request_body = get_request_body(); | |
log_request(json_decode($request_body, true)); | |
$response = buildBigQResponseOk(json_decode($request_body, true)["msgs"]); | |
header("Content-type: application/json"); | |
echo json_encode($response); | |
exit(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment