|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <datadog/dict_writer.h> |
| 4 | +#include <datadog/http_client.h> |
| 5 | + |
| 6 | +#include "httplib.h" |
| 7 | + |
| 8 | +struct HttplibClient : public datadog::tracing::HTTPClient { |
| 9 | + class HeaderWriter final : public datadog::tracing::DictWriter { |
| 10 | + httplib::Headers& headers_; |
| 11 | + |
| 12 | + public: |
| 13 | + explicit HeaderWriter(httplib::Headers& headers) : headers_(headers) {} |
| 14 | + |
| 15 | + void set(std::string_view key, std::string_view value) override { |
| 16 | + auto found = headers_.find(std::string(key)); |
| 17 | + if (found == headers_.cend()) { |
| 18 | + headers_.emplace(key, value); |
| 19 | + } else { |
| 20 | + found->second = value; |
| 21 | + } |
| 22 | + } |
| 23 | + }; |
| 24 | + httplib::Client cli; |
| 25 | + |
| 26 | + HttplibClient(std::string_view agent_url) : cli(agent_url.data()) {} |
| 27 | + |
| 28 | + datadog::tracing::Expected<void> post( |
| 29 | + const URL& url, HeadersSetter set_headers, std::string body, |
| 30 | + ResponseHandler on_response, ErrorHandler on_error, |
| 31 | + std::chrono::steady_clock::time_point deadline) override { |
| 32 | + httplib::Request req; |
| 33 | + req.method = "POST"; |
| 34 | + req.path = url.path; |
| 35 | + req.body = body; |
| 36 | + |
| 37 | + HeaderWriter writer(req.headers); |
| 38 | + set_headers(writer); |
| 39 | + |
| 40 | + auto result = cli.send(req); |
| 41 | + if (result.error() != httplib::Error::Success) { |
| 42 | + on_error(datadog::tracing::Error{ |
| 43 | + datadog::tracing::Error::Code::CURL_HTTP_CLIENT_ERROR, |
| 44 | + to_string(result.error())}); |
| 45 | + } |
| 46 | + return {}; |
| 47 | + } |
| 48 | + |
| 49 | + // Wait until there are no more outstanding requests, or until the specified |
| 50 | + // `deadline`. |
| 51 | + inline void drain(std::chrono::steady_clock::time_point deadline) override { |
| 52 | + return; |
| 53 | + }; |
| 54 | + |
| 55 | + // Return a JSON representation of this object's configuration. The JSON |
| 56 | + // representation is an object with the following properties: |
| 57 | + // |
| 58 | + // - "type" is the unmangled, qualified name of the most-derived class, e.g. |
| 59 | + // "datadog::tracing::Curl". |
| 60 | + // - "config" is an object containing this object's configuration. "config" |
| 61 | + // may be omitted if the derived class has no configuration. |
| 62 | + inline std::string config() const override { |
| 63 | + return "{\"type\": \"httplib\"}"; |
| 64 | + }; |
| 65 | + |
| 66 | + ~HttplibClient() = default; |
| 67 | +}; |
0 commit comments