Networking example

Below you can find source code of a networking example that showcases usage of the libbase functionality for performing network requests. This example is located in the /examples/networking/ directory in the repository and - if enabled - will be built along the libbase library itself.

CMakeLists.txt
 1add_executable(networking "")
 2
 3target_compile_options(networking
 4  PRIVATE
 5    ${LIBBASE_COMPILE_FLAGS}
 6)
 7
 8target_link_libraries(networking
 9  PRIVATE
10    libbase
11    libbase_net
12)
13
14target_sources(networking
15  PRIVATE
16    main.cc
17)
main.cc
  1#include <thread>
  2
  3#include "base/bind.h"
  4#include "base/callback.h"
  5#include "base/init.h"
  6#include "base/logging.h"
  7#include "base/message_loop/run_loop.h"
  8#include "base/net/init.h"
  9#include "base/net/simple_url_loader.h"
 10#include "base/net/url_request.h"
 11#include "base/sequence_checker.h"
 12#include "base/timer/elapsed_timer.h"
 13
 14void LogNetResponse(const base::net::ResourceResponse& response) {
 15  LOG(INFO) << "Result: " << static_cast<int>(response.result);
 16  LOG(INFO) << "HTTP code: " << response.code;
 17  LOG(INFO) << "Final URL: " << response.final_url;
 18  LOG(INFO) << "Downloaded " << response.data.size() << " bytes";
 19  LOG(INFO) << "Latency: " << response.timing_connect.InMilliseconds() << "ms";
 20  LOG(INFO) << "Headers";
 21  for (const auto& [h, v] : response.headers) {
 22    LOG(INFO) << "  " << h << ": " << v;
 23  }
 24  LOG_IF(INFO, !response.data.empty())
 25      << "Content:\n"
 26      << std::string{response.data.begin(), response.data.end()};
 27}
 28
 29void NetExampleGet() {
 30  base::RunLoop run_loop{};
 31
 32  // Try to download and signal on finish
 33  base::net::SimpleUrlLoader::DownloadUnbounded(
 34      base::net::ResourceRequest{"https://www.google.com/robots.txt"}
 35          .WithHeadersOnly()
 36          .WithTimeout(base::Seconds(5)),
 37      base::BindOnce([](base::net::ResourceResponse response) {
 38        LogNetResponse(response);
 39      }).Then(run_loop.QuitClosure()));
 40
 41  // Runs all tasks until the quit callback is called
 42  run_loop.Run();
 43}
 44
 45void NetExamplePost() {
 46  base::RunLoop run_loop{};
 47
 48  // Try to download and signal on finish
 49  base::net::SimpleUrlLoader::DownloadUnbounded(
 50      base::net::ResourceRequest{"https://httpbin.org/post"}
 51          .WithHeaders({"Content-Type: application/json"})
 52          .WithPostData("{\"key\": \"value\"}")
 53          .WithTimeout(base::Seconds(5)),
 54      base::BindOnce([](base::net::ResourceResponse response) {
 55        LogNetResponse(response);
 56      }).Then(run_loop.QuitClosure()));
 57
 58  run_loop.Run();
 59}
 60
 61class UrlRequestExampleUser : public base::net::UrlRequest::Client {
 62 public:
 63  UrlRequestExampleUser(base::OnceClosure finished_closure)
 64      : finished_closure_(std::move(finished_closure)), request_(this) {}
 65
 66  void Download(base::net::ResourceRequest request) {
 67    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 68    request_.Start(std::move(request));
 69  }
 70
 71  void OnResponseStarted(const base::net::UrlRequest* request,
 72                         int code,
 73                         std::string final_url,
 74                         std::map<std::string, std::string> headers) override {
 75    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 76    DCHECK_EQ(request, &request_);
 77
 78    LOG(INFO) << __FUNCTION__ << "() code: " << code;
 79    LOG(INFO) << __FUNCTION__ << "() final_url: " << final_url;
 80    for (const auto& [k, v] : headers) {
 81      LOG(INFO) << __FUNCTION__ << "() header[" << k << "]: " << v;
 82    }
 83  }
 84
 85  void OnWriteData(const base::net::UrlRequest* request,
 86                   std::vector<uint8_t> chunk) override {
 87    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 88    DCHECK_EQ(request, &request_);
 89
 90    LOG(INFO) << __FUNCTION__ << "() received bytes: " << chunk.size();
 91  }
 92
 93  void OnRequestFinished(const base::net::UrlRequest* request,
 94                         base::net::Result result) override {
 95    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
 96    DCHECK_EQ(request, &request_);
 97
 98    LOG(INFO) << __FUNCTION__ << "() result: " << static_cast<int>(result);
 99    std::move(finished_closure_).Run();
100  }
101
102 private:
103  SEQUENCE_CHECKER(sequence_checker_);
104  base::OnceClosure finished_closure_;
105  base::net::UrlRequest request_;
106};
107
108void NetExampleUrlRequest() {
109  base::RunLoop run_loop;
110
111  UrlRequestExampleUser url_request_user{run_loop.QuitClosure()};
112  url_request_user.Download(
113      base::net::ResourceRequest{"https://www.google.com/robots.txt"}
114          .WithTimeout(base::Seconds(5)));
115
116  run_loop.Run();
117}
118
119int main(int argc, char* argv[]) {
120  base::Initialize(argc, argv, base::InitOptions{});
121  base::net::Initialize(base::net::InitOptions{});
122
123  const auto timer = base::ElapsedTimer{};
124
125  NetExampleGet();
126  NetExamplePost();
127  NetExampleUrlRequest();
128
129  LOG(INFO) << "Example finished in " << timer.Elapsed().InMillisecondsF()
130            << "ms";
131
132  base::net::Deinitialize();
133  base::Deinitialize();
134  return 0;
135}