C++ httplib 解读1

第一篇博客,记录下最近在看的一个开源库cpp-httplib。

1
2
起因:要做一个设备的本地服务端,因为要调用一个本地的动态库(windows平台),就选择了这个库作为网络库。
优势:header only,讲人话就是只需要包含一个头文件就行了,方便。也可以使用它自带的python脚本把它劈开成头文件和源文件,避免“强迫症”觉得头文件到处展开不好。然后对于常用的操作 get post put delete option patch 都进行了一个封装,只需要定义一个处理函数就行了,加上c11的lambda表达式,让人觉得比PHP还天下第一??
1
2
3
4
5
6
7
8
9
10
11
12
  using namespace httplib;

  Server svr;

  svr.Get("/hi", [](const Request& req, Response& res) {
    res.set_content("Hello World!", "text/plain");
  });

  svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
    auto numbers = req.matches[1];
    res.set_content(numbers, "text/plain");
  });

嗯,上面就是一个Server的用法,Client也很简单

1
2
3
4
5
6
  httplib::Client cli("localhost", 1234);

  auto res = cli.Get("/hi");
  if (res && res->status == 200) {
    std::cout << res->body << std::endl;
  }

其他的示例可以看上面的官方文档,有一个问题就是我使用成员函数指针作为回调时,用std::bind 绑定对象,总会出现一个错误,开发环境是vs2015,所以只能在lambda 里面去调用这个类的成员函数,看着比较low,如果有解决方法的烦请在评论区告知在下。

然后代码解析就先从最简单的Client::Get 作为突破口。
然后又从最简单的单参数重载版本入手
然后Client的成员就自己下载一下看,贴上来感觉有凑字数的嫌疑……

1
2
3
inline std::shared_ptr<Response> Client::Get(const char *path) {
  return Get(path, Headers(), Progress());
}

解读:调用了另一个重载版本,使用Progress为默认构造functional,可以使用判断时类似nullptr 作为要给false。

1
2
3
4
5
6
7
8
9
10
11
inline std::shared_ptr<Response>
Client::Get(const char *path, const Headers &headers, Progress progress) {
  Request req;
  req.method = "GET";
  req.path = path;
  req.headers = headers;
  req.progress = std::move(progress);

  auto res = std::make_shared<Response>();
  return send(req, *res) ? res : nullptr;
}

解读:Request 中定义了请求的方法,路径,还有 header,而header的类型是mulitmap 的,然后此处使用了一个send函数,内部对request response 形成了一个封装,还有就是url中的params 是自己添加到path里面的,当然还有使用了params的重载类型,这里就不讲了。

//起个头~~~~