備忘録

備忘録

C++でHTTPサーバ、クライアントを作る方法

Ⅰ. はじめに

タイトルの通り「C++でHTTPサーバ、クライアントを作る方法」です。

以下のライブラリを使います。
https://github.com/yhirose/cpp-httplib

Ⅱ. HTTPサーバ

サンプルプログラム
#pragma comment(lib, "ws2_32.lib")

#include "httplib.h"
#include <iostream>

int main(void)
{
  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");
  });

  svr.listen("localhost", 1234);
  return 0;
}
実行結果

f:id:kagasu:20180721160815p:plain

Ⅲ. HTTPクライアント

サンプルプログラム
#pragma comment(lib, "ws2_32.lib")

#include "httplib.h"
#include <iostream>

using namespace std;

int main(void)
{
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  httplib::SSLClient cli("example.com", 80);
#else
  httplib::Client cli("example.com", 80);
#endif

  auto res = cli.Get("/");
  if (res) {
    cout << res->status << endl;
    cout << res->get_header_value("Content-Type") << endl;
    cout << res->body << endl;
  }

  return 0;
}
実行結果

f:id:kagasu:20180721161010p:plain