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 小时前
HTTP 协议的基本格式和 fiddler 的用法
网络协议·http·fiddler
C^h3 小时前
c++ string
开发语言·c++
raindayinrain3 小时前
c++高性能--原子操作,无锁编程,操作顺序
开发语言·c++·性能优化
学逆向的3 小时前
C++ 合并命名空间
开发语言·c++·网络安全
Zhao-Jichao3 小时前
VS2026 打包 C++ 程序生成 EXE,借助 Installer Project 扩展工具
开发语言·c++
小徐不徐说4 小时前
C++ 接口与插件设计:从工厂注册到 Qt 动态插件
数据库·c++·qt·系统架构·程序设计
大都督会赢的5 小时前
C++第一节课
开发语言·c++
UIU1145 小时前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
TMedical5 小时前
MedPlanning 截骨模拟矫形功能
c++·图像处理·人工智能·qt·健康医疗
qq_406981036 小时前
共享变量一 关于extern与const
开发语言·c++