Refactor HTTP request handling and data extraction

- Improved handling of HTTP requests and extraction of response data.
This commit is contained in:
Jeroen De Meerleer 2024-06-03 13:52:02 +02:00
parent d829ac06b0
commit 98fa29d900
No known key found for this signature in database
GPG Key ID: 3B23D1B3498D7641

View File

@ -3,52 +3,52 @@ require 'vendor/autoload.php';
require 'config.php'; require 'config.php';
if($_SERVER["REQUEST_URI"] == '/metrics' || php_sapi_name() == 'cli') { if($_SERVER["REQUEST_URI"] == '/metrics' || php_sapi_name() == 'cli') {
foreach ($config as $key => &$c) { foreach ($config as $key => &$c) {
if(isset($c['command'])) { if(isset($c['command'])) {
$output=null; $output=null;
$retval=null; $retval=null;
exec($c['command'], $output, $retval); exec($c['command'], $output, $retval);
$output = implode("\n", $output); $output = implode("\n", $output);
} elseif(isset($c['http'])) { } elseif(isset($c['http'])) {
$client = new GuzzleHttp\Client(); $client = new GuzzleHttp\Client();
$options = []; $options = [];
$output = NULL; $output = NULL;
if (isset($c['http']['proxy'])) { if (isset($c['http']['proxy'])) {
$options['proxy'] = $c['http']['proxy']; $options['proxy'] = $c['http']['proxy'];
} }
if (isset($c['http']['data']) && $c['http']['data'] == 'responsetime') { if (isset($c['http']['data']) && $c['http']['data'] == 'responsetime') {
$options['on_stats'] = function (GuzzleHttp\TransferStats $stats) use (&$output) { $options['on_stats'] = function (GuzzleHttp\TransferStats $stats) use (&$output) {
$output = $stats->getTransferTime(); $output = $stats->getTransferTime();
}; };
} }
$res = $client->request('GET', $c['http']['url'], $options);
$res = $client->request('GET', $c['http']['url'], $options); if (isset($c['http']['data']) && $c['http']['data'] == 'responsebody') {
$output = $res->getBody()->getContents();
}
}
if (isset($c['http']['data']) && $c['http']['data'] == 'responsebody') { if(isset($c['jsonelem'])) {
$output = $res->getBody()->getContents(); $c['value'] = getArrayValue($c['jsonelem'], json_decode($output, true));
} } else {
} $c['value'] = $output;
}
}
if(isset($c['jsonelem'])) { $loader = new \Twig\Loader\FilesystemLoader('templates');
$c['value'] = getArrayValue($c['jsonelem'], json_decode($output, true)); $twig = new \Twig\Environment($loader, [
} else { 'cache' => 'twig_cache',
$c['value'] = $output; ]);
} echo $twig->render('metrics.twig', ['config' => $config]);
}
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [
'cache' => 'twig_cache',
]);
echo $twig->render('metrics.twig', ['config' => $config]);
} }
function getArrayValue($elem, $array) { function getArrayValue($elem, $array) {
$elem = explode('.', $elem); $elem = explode('.', $elem);
$new_array = $array; $new_array = $array;
foreach ($elem as $i) { foreach ($elem as $i) {
$new_array = $new_array[$i]; $new_array = $new_array[$i];
} }
return $new_array; return $new_array;
} }