C++编程: 基于cpp-httplib和nlohmann/json实现简单的HTTP Server

0. 引言

本文基于 cpp-httplibnlohmann/json 实现简单的 HTTPS Server 实例代码,这两个库均是head-only的。

1. 完整实例代码

如下实例程序修改自example/server.cc

#include <httplib.h>

#include <chrono>
#include <cstdio>
#include <nlohmann/json.hpp>

using namespace httplib;
using json = nlohmann::json;

#define SERVER_CERT_FILE "./cert.pem"
#define SERVER_PRIVATE_KEY_FILE "./key.pem"

json dump_headers_json(const Headers &headers) {
   
    
    
  json j;
  for (const auto &x : headers) {
   
    
    
    j[x.first] = x.second;
  }
  return j;
}

json log_json(const Request &req, const Response &res) {
   
    
    
  json j;

  j["request"]["method"] = req.method;
  j["request"]["version"] = req.version;
  j["request"]["path"] = req.path;

  json query_params = json::object();
  for (const auto &x : req.params) {
   
    
    
    query_params[x.first] = x.second;
  }
  j["request"]