http_client.h
1 // Copyright 2018, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 
5 #pragma once
6 
7 #include <boost/beast/http/dynamic_body.hpp>
8 #include <boost/beast/http/message.hpp>
9 
10 #include "strings/stringpiece.h"
11 
12 namespace util {
13 class IoContext;
14 class FiberSyncSocket;
15 
16 namespace http {
17 
18 /*
19  Single threaded, fiber-friendly synchronous client: Upon IO block, the calling fiber blocks
20  but the thread can switch to other active fibers.
21 */
22 class Client {
23  public:
24  using Response = boost::beast::http::response<boost::beast::http::dynamic_body>;
25  using Verb = boost::beast::http::verb;
26 
27  explicit Client(IoContext* io_context);
28  ~Client();
29 
30  boost::system::error_code Connect(StringPiece host, StringPiece service);
31 
32  boost::system::error_code Send(Verb verb, StringPiece url, StringPiece body, Response* response);
33  boost::system::error_code Send(Verb verb, StringPiece url, Response* response) {
34  return Send(verb, url, StringPiece{}, response);
35  }
36 
37  void Shutdown();
38 
39  bool IsConnected() const;
40 
41  void set_connect_timeout_ms(uint32_t ms) { connect_timeout_ms_ = ms; }
42 
43  // Adds header to all future requests.
44  void AddHeader(std::string name, std::string value) {
45  headers_.emplace_back(std::move(name), std::move(value));
46  }
47 
48  private:
49  IoContext& io_context_;
50  uint32_t connect_timeout_ms_ = 2000;
51 
52  using HeaderPair = std::pair<std::string, std::string>;
53 
54  std::vector<HeaderPair> headers_;
55  std::unique_ptr<FiberSyncSocket> socket_;
56 };
57 
58 } // namespace http
59 } // namespace util
60