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

相关推荐
程序喵大人3 小时前
写C++十年,我现在怎么设计类和模块?(附真实项目结构)
开发语言·c++·类和模板
liulilittle4 小时前
Unix/Linux 平台通过 IP 地址获取接口名的 C++ 实现
linux·开发语言·c++·tcp/ip·unix·编程语言
深耕AI4 小时前
【MFC 小白日记】对话框编辑器里“原型图像”到底要不要勾?3 分钟看懂!
c++·编辑器·mfc
Nerd Nirvana4 小时前
C++编程——异步处理、事件驱动编程和策略模式
开发语言·c++·策略模式·嵌入式开发·事件驱动·异步处理
一拳一个呆瓜4 小时前
【MFC】对话框节点属性:Condition(条件)
c++·mfc
快去睡觉~4 小时前
力扣416:分割等和子集
数据结构·c++·算法·leetcode·职场和发展·动态规划
会当临5 小时前
【c++】四种类型转换形式
开发语言·c++
代码程序猿RIP5 小时前
【Linux】线程封装
linux·jvm·c++
数据爬坡ing5 小时前
C++ 类库管理系统的分析与设计:面向对象开发全流程实践
java·运维·开发语言·c++·软件工程·软件构建·运维开发