Horizon
http_client.hpp
1 #pragma once
2 #include "nlohmann/json.hpp"
3 #include <curl/curl.h>
4 #include <string>
5 #include <list>
6 
7 namespace horizon::HTTP {
8 class Client {
9  friend size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp);
10 
11 public:
12  Client();
13  void set_auth(const std::string &user, const std::string &passwd);
14  void set_timeout(int timeout);
15  void append_header(const char *header);
16  void append_header(const std::string &header)
17  {
18  append_header(header.c_str());
19  }
20  void clear_headers();
21  using ResponseHeaders = std::list<std::string>;
22 
23  std::string get(const std::string &url);
24  std::string post(const std::string &url, const std::string &postdata = "");
25  std::string post_form(const std::string &url, const std::vector<std::pair<std::string, std::string>> &fields);
26  const ResponseHeaders &get_response_headers() const
27  {
28  return headers_received;
29  }
30 
31  ~Client();
32 
33 private:
34  CURL *curl = nullptr;
35  curl_slist *header_list = nullptr;
36  char errbuf[CURL_ERROR_SIZE];
37 
38  std::string response;
39  std::string postdata;
40 
41  class PostBuffer {
42  public:
43  const char *readptr = nullptr;
44  size_t sizeleft = 0;
45  };
46  PostBuffer post_buffer;
47  ResponseHeaders headers_received;
48 };
49 
50 using json = nlohmann::json;
51 
52 class RESTClient : public HTTP::Client {
53 public:
54  RESTClient(const std::string &base);
55 
56  json get(const std::string &url);
57  json post(const std::string &url, const json &postdata = json());
58 
59 private:
60  const std::string base_url;
61 };
62 } // namespace horizon::HTTP
Definition: http_client.hpp:8
Definition: http_client.hpp:52
a class to store JSON values
Definition: json.hpp:177
basic_json<> json
default JSON class
Definition: json_fwd.hpp:62