EcsMetadataFetcher.cc 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 1999-2019 Alibaba Cloud All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <alibabacloud/core/Url.h>
  17. #include <sstream>
  18. #include <memory>
  19. #include "EcsMetadataFetcher.h"
  20. #include "CurlHttpClient.h"
  21. namespace AlibabaCloud {
  22. EcsMetadataFetcher::EcsMetadataFetcher() {
  23. }
  24. EcsMetadataFetcher::~EcsMetadataFetcher() {
  25. }
  26. std::string EcsMetadataFetcher::roleName()const {
  27. return roleName_;
  28. }
  29. void EcsMetadataFetcher::setRoleName(const std::string & roleName) {
  30. roleName_ = roleName;
  31. }
  32. std::string EcsMetadataFetcher::getMetadata() {
  33. return getMetadata(METADATA_SERVICE_HOST, URL_IN_ECS_METADATA);
  34. }
  35. std::string EcsMetadataFetcher::getMetadata(const std::string host,
  36. const std::string in_path) {
  37. std::stringstream path;
  38. path << in_path << roleName_;
  39. Url credentialUrl;
  40. credentialUrl.setHost(host);
  41. credentialUrl.setPath(path.str());
  42. auto client = std::make_shared<CurlHttpClient>();
  43. HttpRequest request;
  44. request.setUrl(credentialUrl);
  45. auto outcome = client->makeRequest(request);
  46. if (outcome.isSuccess())
  47. return std::string(outcome.result().body(), outcome.result().bodySize());
  48. else
  49. return outcome.error().errorCode();
  50. }
  51. } // namespace AlibabaCloud