|
| 1 | +#include "opentelemetry/ext/http/client/http_client_factory.h" |
| 2 | +#include "opentelemetry/ext/http/common/url_parser.h" |
| 3 | +#include "tracer_common.hpp" |
| 4 | + |
| 5 | +namespace |
| 6 | +{ |
| 7 | + |
| 8 | +void sendRequest(const std::string &url) |
| 9 | +{ |
| 10 | + auto http_client = opentelemetry::ext::http::client::HttpClientFactory::CreateSync(); |
| 11 | + |
| 12 | + // start active span |
| 13 | + opentelemetry::trace::StartSpanOptions options; |
| 14 | + options.kind = opentelemetry::trace::SpanKind::kClient; // client |
| 15 | + opentelemetry::ext::http::common::UrlParser url_parser(url); |
| 16 | + |
| 17 | + std::string span_name = url_parser.path_; |
| 18 | + auto span = get_tracer("http-client") |
| 19 | + ->StartSpan(span_name, |
| 20 | + {{"http.url", url_parser.url_}, |
| 21 | + {"http.scheme", url_parser.scheme_}, |
| 22 | + {"http.method", "GET"}}, |
| 23 | + options); |
| 24 | + auto scope = get_tracer("http-client")->WithActiveSpan(span); |
| 25 | + |
| 26 | + opentelemetry::ext::http::client::Result result = http_client->Get(url); |
| 27 | + if (result) |
| 28 | + { |
| 29 | + // set span attributes |
| 30 | + auto status_code = result.GetResponse().GetStatusCode(); |
| 31 | + span->SetAttribute("http.status_code", status_code); |
| 32 | + result.GetResponse().ForEachHeader([&span](opentelemetry::nostd::string_view header_name, |
| 33 | + opentelemetry::nostd::string_view header_value) { |
| 34 | + span->SetAttribute("http.header." + std::string(header_name.data()), header_value); |
| 35 | + return true; |
| 36 | + }); |
| 37 | + |
| 38 | + if (status_code >= 400) |
| 39 | + { |
| 40 | + span->SetStatus(opentelemetry::trace::StatusCode::kError); |
| 41 | + } |
| 42 | + } |
| 43 | + else |
| 44 | + { |
| 45 | + span->SetStatus(opentelemetry::trace::StatusCode::kError, |
| 46 | + "Response Status :" + |
| 47 | + std::to_string(static_cast<typename std::underlying_type< |
| 48 | + opentelemetry::ext::http::client::SessionState>::type>( |
| 49 | + result.GetSessionState()))); |
| 50 | + } |
| 51 | + // end span and export data |
| 52 | + span->End(); |
| 53 | +} |
| 54 | + |
| 55 | +} // namespace |
| 56 | + |
| 57 | +int main(int argc, char *argv[]) |
| 58 | +{ |
| 59 | + initTracer(); |
| 60 | + constexpr char default_host[] = "localhost"; |
| 61 | + constexpr char default_path[] = "/helloworld"; |
| 62 | + constexpr uint16_t default_port = 8800; |
| 63 | + uint16_t port; |
| 64 | + |
| 65 | + // The port the validation service listens to can be specified via the command line. |
| 66 | + if (argc > 1) |
| 67 | + { |
| 68 | + port = atoi(argv[1]); |
| 69 | + } |
| 70 | + else |
| 71 | + { |
| 72 | + port = default_port; |
| 73 | + } |
| 74 | + |
| 75 | + std::string url = "http://" + std::string(default_host) + ":" + std::to_string(port) + |
| 76 | + std::string(default_path); |
| 77 | + sendRequest(url); |
| 78 | +} |
0 commit comments