一、代码示例
#include <lithium_http_server.hh> #include <lithium_pgsql.hh> #include "symbols.hh" using namespace li; int main() { // 创建 PostgreSQL 数据库连接 pgsql_database db = pgsql_database( s::host = "localhost", s::database = "your_database", s::user = "your_username", s::password = "your_password", s::port = 5432 ); // 定义 ORM 模式 auto schema = sql_orm_schema(db, "users") .fields(s::id = int(), s::name = std::string(), s::email = std::string()); // 连接 ORM 模式 auto users = schema.connect(); // 定义 HTTP API http_api api; api.get("/users") = [&](http_request& req, http_response& res) { // 查询所有用户 auto result = users(s::select = s::all); res.write(result); }; api.post("/users") = [&](http_request& req, http_response& res) { // 创建新用户 auto new_id = users.insert(s::name = req.get_parameter("name"), s::email = req.get_parameter("email")); res.write("User created with id: ", new_id); }; api.get("/users/:id") = [&](http_request& req, http_response& res) { // 根据 ID 查询用户 auto user = users.find_one(s::id = req.url_parameters().id); if (user) { res.write(*user); } else { res.write("User not found"); } }; api.put("/users/:id") = [&](http_request& req, http_response& res) { // 更新用户信息 auto updated = users.update(s::id = req.url_parameters().id, s::name = req.get_parameter("name"), s::email = req.get_parameter("email")); res.write("User updated: ", updated); }; api.delete("/users/:id") = [&](http_request& req, http_response& res) { // 删除用户 auto deleted = users.remove(s::id = req.url_parameters().id); res.write("User deleted: ", deleted); }; // 启动 HTTP 服务器 http_serve(api, 8080); }
标签:web,matt,http,users,res,req,42,api,id From: https://www.cnblogs.com/pearlcity/p/18408958