c++工程如何提供http服务接口
在 C++ 工程里给类似 /index/api/
的服务,基本步骤如下:
- 选一个HTTP服务框架;
- 起一条监听线程(或线程池);
- 把路径-处理函数注册进去;
下面是 2 种简单的方案。
方案 A:Crow(Header-only,最简单)
依赖:C++14 及以上;Boost(可选,仅 header);OpenSSL(可选)。
# 1. 拉源码
git clone https://github.com/CrowCpp/Crow.git
cd Crow
# 2. 写 main.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();
}
g++ -std=c++17 main.cpp -lpthread -o server
./server
浏览器 http://localhost:8080/index/api/
即可看到 JSON 返回。
方案 B:cpp-httplib(Header-only,零依赖)
特点:单头文件,仅依赖系统 libc;适合嵌入式/小工具。
#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
。