absl::StatusOr CurlHttpGet()

in cpp/acs_agent_helper.cc [103:155]


absl::StatusOr<std::string> CurlHttpGet(const std::string& url,
                                        const std::string& header) {
  CURL* curl;
  CURLcode res;
  std::string read_buffer;
  curl = curl_easy_init();
  if (curl == nullptr) {
    ABSL_LOG(ERROR) << "Failed to initialize curl.";
    return absl::InternalError("Failed to initialize curl.");
  }

  // Set URL.
  res = curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  if (res != CURLE_OK) {
    ABSL_LOG(ERROR) << "Failed to set URL: " << url;
    curl_easy_cleanup(curl);
    return absl::InternalError(absl::StrCat(
        "Failed to set URL: ", url, " with error: ", curl_easy_strerror(res)));
  }

  // Set header.
  struct curl_slist* headers = nullptr;
  headers = curl_slist_append(headers, header.c_str());
  res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  if (res != CURLE_OK || headers == nullptr) {
    ABSL_LOG(ERROR) << "Failed to set header: " << header;
    curl_easy_cleanup(curl);
    if (headers != nullptr) {
      curl_slist_free_all(headers);
    }
    return absl::InternalError(
        absl::StrCat("Failed to set header: ", header,
                     " with error: ", curl_easy_strerror(res)));
  }

  // Set the write callback function and its data.
  // No need to check the return value as they will both return CURLE_OK.
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &read_buffer);

  res = curl_easy_perform(curl);
  curl_easy_cleanup(curl);
  curl_slist_free_all(headers);
  if (res != CURLE_OK) {
    ABSL_LOG(ERROR) << "curl_easy_perform() failed: "
                    << curl_easy_strerror(res);
    return absl::InternalError(absl::StrCat(
        "curl_easy_perform() failed with error: ", curl_easy_strerror(res)));
  }
  ABSL_VLOG(1) << "Got metadata for key: " << url
               << " and its value is: " << read_buffer;
  return read_buffer;
}