Commit 6a6afa94 authored by Jakob Moser's avatar Jakob Moser
Browse files

Document code

parent 5bd7051c
Loading
Loading
Loading
Loading
+14 −3
Original line number Diff line number Diff line
@@ -16,23 +16,34 @@ $services = [
// send one. If we hadn't written this, the content type would be text/html.
header("Content-Type: application/json; charset=utf-8");

// A "curl multi handle". Can be filled with multiple "curl handles" (each corresponding to one HTTPS request)
// that can then be executed simultaneously.
$multi_handle = curl_multi_init();
$handles = [];

foreach($services as $service) {
  // Initialize a curl handle, i.e. prepare a single request. This will not yet make the request.
  $ch = curl_init("https://{$service['host']}");

  // We want curl to return the response (and not just echo it back to the requester). This is the
  // normal option you'd also expect when using e.g., Python's `requests` library.
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $handles[] = $ch;
  
  // Append the handle to the array of handles (we need it later to get the response code) and add
  // it to the multi handle (which we need to make the requests in batch).
  $handles[] = $ch;
  curl_multi_add_handle($multi_handle, $ch);
}

$active_requests = -1;
$active_requests = 0;
do {
  // Execute all requests simultaneously
  curl_multi_exec($multi_handle, $active_requests);
  // Wait until at least one request is finished
  curl_multi_select($multi_handle);
} while($active_requests > 0);
} while($active_requests > 0);  // Repeat until all requests are finished

// Get the response code from each request (accessed via the handles, and add it to the response JSON).
foreach($handles as $index => $handle) {
  $services[$index]["status"] = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
}