仮想計算機構

IT業界と無縁な派遣社員のブログ

Visual Studio で cpp-httplib のサンプルプログラムを動かす

GitHub - yhirose/cpp-httplib: A C++ header-only HTTP/HTTPS server and client library
cpp-httplib はヘッダーファイルのみの HTTP/HTTPS ライブラリです。本記事では本家サイトにあるサンプルを動かすことを目標とします。

0.環境

OS : WIndows 10
IDE : Microsoft Visual Studio Community 2019 Version 16.8.4

README には

NOTE: cpp-httplib officially supports only the latest Visual Studio. It might work with former versions of Visual Studio, but I can no longer verify it. Pull requests are always welcome for the older versions of Visual Studio unless they break the C++11 conformance.

NOTE: Windows 8 or lower, Visual Studio 2013 or lower, and Cygwin on Windows are not supported.

と書いてありますので OS や IDE が古い方はご注意ください。

1.プログラム

本家サイトにあるサンプルプログラムは下記の通りです。今回はWindowsで動かすのでヘッダー部分は書き換えておきます。

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

int main(void)
{
  using namespace httplib;

  Server svr;

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

  // Match the request path against a regular expression
  // and extract its captures
  svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
    auto numbers = req.matches[1];
    res.set_content(numbers, "text/plain");
  });

  // Capture the second segment of the request path as "id" path param
  svr.Get("/users/:id", [&](const Request& req, Response& res) {
    auto user_id = req.path_params.at("id");
    res.set_content(user_id, "text/plain");
  });

  // Extract values from HTTP headers and URL query params
  svr.Get("/body-header-param", [](const Request& req, Response& res) {
    if (req.has_header("Content-Length")) {
      auto val = req.get_header_value("Content-Length");
    }
    if (req.has_param("key")) {
      auto val = req.get_param_value("key");
    }
    res.set_content(req.body, "text/plain");
  });

  svr.Get("/stop", [&](const Request& req, Response& res) {
    svr.stop();
  });

  svr.listen("localhost", 1234);
}

ヘッダーファイル httplib.h は Github ページからダウンロードして、上記のファイルと同じディレクトリに置きます。Visual Studio 上では次のような構成になります。


2.ビルドと実行結果

「ソリューションのビルド」「デバッグなしで開始」を押下します。何も表示されていないコンソールが立ち上がると思います。コンソールは無視して localhost にアクセスしてみましょう。

2.2.ユーザー名

ユーザー名をそのまま表示します。
http://localhost:1234/users/777


2.3.数値

1桁以上の数値であれば、その数字が表示されます。
http://localhost:1234/numbers/0123456789


2.5.停止

http://localhost:1234/stop

上記 URL にアクセスするとコンソールにメッセージが表示されます。

サーバーが停止しているので Hello world を表示させようとしても次のような画面が表示されます。

サンプルプログラムを動きを確認できたので今回は以上です。