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