「C++でHTTPSサーバを立てるのってどうやるんだろう」と思ってしらべてみた。
具体的にはcpp-htttplibを使用した。
まずcpp-httplibをcloneしてくる
git clone https://github.com/yhirose/cpp-httplib.git
同じディレクトリに移動して自己証明の証明書ファイルを作る(参考)
openssl genrsa 2048 > server.key
openssl req -new -key server.key > server.csr
openssl x509 -days 3650 -req -sha256 -signkey server.key < server.csr > server.crt
openssl x509 -text < server.crt # 生成した証明書の確認
main.cppを同じディレクトリに作る
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include "httplib.h"
int main(void)
{
using namespace httplib;
SSLServer svr("./server.crt", "./server.key");
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.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);
}
ビルドする
g++ -pthread main.cpp httplib.h -lssl -lcrypto
-lssl -lcryptoを忘れると次のようなエラーが出てしまう
undefined reference to `SSL_shutdown'
動作チェック
$ ab -n 10000 -c 6 https://localhost:1234/hi
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software:
Server Hostname: localhost
Server Port: 1234
SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256
Server Temp Key: X25519 253 bits
TLS Server Name: localhost
Document Path: /hi
Document Length: 12 bytes
Concurrency Level: 6
Time taken for tests: 14.775 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 1070000 bytes
HTML transferred: 120000 bytes
Requests per second: 676.80 [#/sec] (mean)
Time per request: 8.865 [ms] (mean)
Time per request: 1.478 [ms] (mean, across all concurrent requests)
Transfer rate: 70.72 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 7 1.5 7 32
Processing: 0 2 1.2 2 26
Waiting: 0 1 0.8 1 17
Total: 3 9 1.6 8 33
Percentage of the requests served within a certain time (ms)
50% 8
66% 9
75% 9
80% 9
90% 10
95% 11
98% 13
99% 14
100% 33 (longest request)