c++工程如何提供http服务接口

在 C++ 工程里给类似 /index/api/ 的服务,基本步骤如下:

  1. 选一个HTTP服务框架;
  2. 起一条监听线程(或线程池);
  3. 把路径-处理函数注册进去;

下面是 2 种简单的方案。


方案 A:Crow(Header-only,最简单)

依赖:C++14 及以上;Boost(可选,仅 header);OpenSSL(可选)。

bash 复制代码
# 1. 拉源码
git clone https://github.com/CrowCpp/Crow.git
cd Crow
# 2. 写 main.cpp
cpp 复制代码
#include "crow.h"

int main() {
    crow::SimpleApp app;

    CROW_ROUTE(app, "/index/api/")
    ([]() {
        crow::json::wvalue x;
        x["code"] = 200;
        x["msg"]  = "hello from /index/api/";
        return x;
    });

    // 支持 POST/PUT/DELETE 同理
    CROW_ROUTE(app, "/index/api/<int>")
    ([](int id){
        return crow::response(200, "got id=" + std::to_string(id));
    });

    app.port(8080).multithreaded().run();
}
bash 复制代码
g++ -std=c++17 main.cpp -lpthread -o server
./server

浏览器 http://localhost:8080/index/api/ 即可看到 JSON 返回。


方案 B:cpp-httplib(Header-only,零依赖)

特点:单头文件,仅依赖系统 libc;适合嵌入式/小工具。

cpp 复制代码
#include "httplib.h"
using namespace httplib;

int main() {
    Server svr;

    svr.Get("/index/api/", [](const Request&, Response& res){
        res.set_content(R"({"code":200,"msg":"httplib ok"})", "application/json");
    });

    svr.listen("0.0.0.0", 8080);
}

编译同上,g++ -std=c++17 httplib.cpp -lpthread -o server

相关推荐
qq_4232339016 分钟前
C++与Python混合编程实战
开发语言·c++·算法
m0_7155753428 分钟前
分布式任务调度系统
开发语言·c++·算法
CSDN_RTKLIB1 小时前
简化版unique_ptr说明其本质
c++
naruto_lnq1 小时前
泛型编程与STL设计思想
开发语言·c++·算法
m0_748708052 小时前
C++中的观察者模式实战
开发语言·c++·算法
时光找茬2 小时前
【瑞萨AI挑战赛-FPB-RA6E2】+ 从零开始:FPB-RA6E2 开箱测评与 e2 studio 环境配置
c++·单片机·边缘计算
qq_537562672 小时前
跨语言调用C++接口
开发语言·c++·算法
猷咪3 小时前
C++基础
开发语言·c++
CSDN_RTKLIB3 小时前
WideCharToMultiByte与T2A
c++
星火开发设计3 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识