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。

相关推荐
AIgorithmGEEK1 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜3 小时前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso4 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构
慧都产品智能化4 小时前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3
eggwyw6 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
青少儿编程课堂7 小时前
第十八届蓝桥杯青少组图形化真题 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园泡泡堂大挑战解析
c++·python·算法·bfs·信息学竞赛
小七在进步8 小时前
string的实现(3)
开发语言·c++·笔记·visual studio
青少儿编程课堂8 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:Dinic最大流解析
c++·python·算法·bfs·信息学竞赛
草莓熊Lotso9 小时前
【C++ 基于微服务的即时通讯系统】用户服务之Redis数据层落地:会话、登录状态与验证码全封装
数据库·c++·redis·微服务·语音识别
西西弗Sisyphus9 小时前
C++ 里 两个独立的所有权域之间没有建立同步的问题
c++