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。

相关推荐
程序员老陆38 分钟前
C++ 多线程通信方式全景:从共享内存到结构化协调
开发语言·c++
某不知名網友1 小时前
ROS2 核心通信:话题发布与订阅详解
开发语言·c++
C++ 老炮儿的技术栈1 小时前
char (*csConnectName)[256]; 和 char csConnectName [256] 有什么区别
java·c语言·开发语言·c++·人工智能·算法·c
大鹏说大话1 小时前
C++ STL 容器怎么选?vector、list、map、unordered_map 对比
开发语言·c++·list
JMchen1 小时前
性能优化——让Native代码飞起来
android·c++·性能优化
chenbingjie_c2 小时前
手撕 C++ priority_queue:二叉堆 + 模板仿函数 + 模板特化(保姆级逐函数拆解)
开发语言·c++
小小龙学IT2 小时前
C++ Redis 客户端深度解析(hiredis 与 redis-plus-plus)——工业数采实时缓存 C++ 侧实战
c++·redis·缓存
垆边人似月.2 小时前
华为机试题 :最长递增子序列题目
数据结构·c++·算法·华为
开发者联盟league3 小时前
c++11 使用chrono库转换时间点和字符串,计算时间点间隔
java·c++·算法
蜕变的土豆3 小时前
工业监控RTSP取流-实践指南
c++·视频