引言:为什么用C++开发REST API并非儿戏
\nC++传统上与系统编程、游戏和高负载计算相关联。然而近年来,这种语言越来越多地被用于创建Web服务和REST API。为什么?因为C++提供了令人难以置信的性能和对内存的控制,这对于高负载后端解决方案至关重要。
\n在本指南中,我们将在30分钟内使用cpp-httplib库(一个头文件库,无需安装)创建一个完整的C++ REST API。您将学习:
- \n
- 在C++中配置HTTP服务器 \n
- 处理GET、POST、PUT和DELETE请求 \n
- 通过
nlohmann/json处理JSON \n - 编译并运行项目 \n
本材料既适合初学者,也适合希望在Web开发中尝试C++的有经验的开发者。
\n\n步骤1:环境准备和依赖安装
\n我们需要:
\n- \n
- 支持C++17的C++编译器(g++或clang) \n
cpp-httplib库(一个.h文件) \n nlohmann/json库(一个.hpp文件) \n
下载这两个库:
\n# 安装 cpp-httplib\nwget https://raw.githubusercontent.com/yhirose/cpp-httplib/master/httplib.h\n\n# 安装 nlohmann/json\nwget https://raw.githubusercontent.com/nlohmann/json/develop/single_include/nlohmann/json.hpp\n项目结构很简单:
\nmy_rest_api/\n├── main.cpp\n├── httplib.h\n└── json.hpp\n\n步骤2:创建基本HTTP服务器
\n从最小服务器开始,它将监听8080端口并响应GET请求。
\n创建main.cpp文件:
#include "httplib.h"\n#include "json.hpp"\n#include <iostream>\n\nusing namespace httplib;\nusing json = nlohmann::json;\n\nint main() {\n Server svr;\n\n // 对根路径的GET请求\n svr.Get("/", [](const Request& req, Response& res) {\n res.set_content("Hello, REST API on C++!", "text/plain");\n });\n\n std::cout << "Server started on http://localhost:8080" << std::endl;\n svr.listen("0.0.0.0", 8080);\n\n return 0;\n}\n编译并运行:
\ng++ -std=c++17 -pthread -o server main.cpp\n./server\n打开浏览器或使用curl http://localhost:8080——您将看到欢迎消息。服务器运行正常!
步骤3:使用JSON实现CRUD操作
\n现在添加内存数据存储(简单的向量)并实现完整的用户管理REST API。
\n更新后的main.cpp:
#include "httplib.h"\n#include "json.hpp"\n#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n\nusing namespace httplib;\nusing json = nlohmann::json;\n\n// 用户模型\nstruct User {\n int id;\n std::string name;\n std::string email;\n};\n\n// 内存数据库\nstd::vector<User> users;\nint next_id = 1;\n\nint main() {\n Server svr;\n\n // POST /users - 创建用户\n svr.Post("/users", [](const Request& req, Response& res) {\n try {\n auto data = json::parse(req.body);\n User u;\n u.id = next_id++;\n u.name = data["name"];\n u.email = data["email"];\n users.push_back(u);\n\n json response = {{"id", u.id}, {"name", u.name}, {"email", u.email}};\n res.set_content(response.dump(), "application/json");\n } catch (...) {\n res.status = 400;\n res.set_content("{\\"error\\":\\"Invalid JSON\\"}", "application/json");\n }\n });\n\n // GET /users - 获取所有用户列表\n svr.Get("/users", [](const Request& req, Response& res) {\n