C++通过Crow和Mustache实现简单的CMake配置的Web程序

发布于:2025-06-22 ⋅ 阅读:(18) ⋅ 点赞:(0)

        Crow 是一个现代化的 C++ Web 框架,设计目标是提供简洁易用的 API,同时保持高性能。类似于Golang的gin框架,采用了类似的路由机制和请求处理模式,相比于Linux原生的网络编程、Qt的网络编程、Boost.Asio的网络编程,更加简洁,简单。

        Mustache 是一个逻辑无关的模板引擎,支持多种编程语言。它的核心思想是通过简单的标记语法将数据和视图分离,不包含复杂的逻辑控制结构。用于解析html、js、css文件。

        首先编写两个前端文件。

        index.html.mustache

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据表格应用</title>
    <style>
        /* ------------------ 全局样式 ------------------ */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }
        
        /* ------------------ 标题样式 ------------------ */
        h1 {
            color: #2c3e50;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e0e7ed;
        }
        
        /* ------------------ 输入区域样式 ------------------ */
        .input-area {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        #dataInput {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        #dataInput:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        button {
            padding: 12px 25px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #2980b9;
        }
        
        button:active {
            transform: scale(0.98);
        }
        
        /* ------------------ 表格样式 ------------------ */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e0e7ed;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        /* ------------------ 空状态样式 ------------------ */
        .empty-state {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-style: italic;
        }
        
        /* ------------------ 响应式设计 ------------------ */
        @media (max-width: 600px) {
            .input-area {
                flex-direction: column;
            }
            
            button {
                width: 100%;
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>数据表格管理</h1>
        <div class="input-area">
            <input type="text" id="dataInput" placeholder="输入数据并添加到表格...">
            <button onclick="addData()">添加数据</button>
        </div>
        <table id="dataTable">
            <tr>
                <th>数据内容</th>
                <th>操作</th>
            </tr>
            {{> table.html.mustache}}
        </table>
    </div>

    <script>
        // 添加数据到表格
        function addData() {
            var input = document.getElementById('dataInput');
            var data = input.value.trim();
            if (data === '') return;
            
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/submit', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify({ data: data }));
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    input.value = '';
                    fetchData();
                }
            };
        }
        
        // 从服务器获取数据并更新表格
        function fetchData() {
            var table = document.getElementById('dataTable');
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '/table', true);
            xhr.send();
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    table.innerHTML = '<tr><th>数据内容</th><th>操作</th></tr>' + xhr.responseText;
                    // 为删除按钮添加事件监听
                    document.querySelectorAll('button.delete').forEach(btn => {
                        btn.addEventListener('click', function() {
                            var dataValue = this.getAttribute('data-value');
                            deleteData(dataValue);
                        });
                    });
                }
            };
        }
        
        // 从服务器删除指定数据
        function deleteData(value) {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/delete', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify({ data: value }));
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    fetchData();
                }
            };
        }
        
        // 页面加载时初始化数据
        window.addEventListener('DOMContentLoaded', fetchData);
    </script>
</body>
</html>

        table.html.mustache

{{#tableRows}}
<!-- 数据行 - 显示具体数据和删除按钮 -->
<tr>
    <td>{{item}}</td>
    <td>
        <button class="delete" data-value="{{item}}">删除</button>
    </td>
</tr>
{{/tableRows}}

{{^tableRows}}
<!-- 空状态行 - 当没有数据时显示 -->
<tr>
    <td colspan="2" class="empty-state">暂无数据,请添加数据</td>
</tr>
{{/tableRows}}

        然后编写CMakeLists.txt文件:

cmake_minimum_required(VERSION 3.15)
project(crowtest)
set(CMAKE_CXX_STANDARD 17)

list(APPEND CMAKE_PREFIX_PATH "E:/FrameWork/vcpkg/installed/x64-windows")
add_definitions(-DFMT_USE_CPP11=1)
add_definitions(-DFMT_HEADER_ONLY=0)
include_directories("E:/FrameWork/crow/include")
include_directories("E:/FrameWork/asio/include")
include_directories("E:/FrameWork/Mustache-4.1")
add_executable(crowtest main.cpp)
if (WIN32)
    target_link_libraries(crowtest PRIVATE ws2_32 mswsock)
endif()

        最后是main.cpp:

#include <crow.h>
#include <mustache.hpp>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> data;
std::string readFile(const std::string& path) {
    std::ifstream file(path);
    std::string content((std::istreambuf_iterator<char>(file)), 
                         std::istreambuf_iterator<char>());
    return content;
}
int main() {
    crow::SimpleApp app;
    // 加载模板
    kainjow::mustache::mustache indexTemplate(readFile("../templates/index.html.mustache"));
    kainjow::mustache::mustache tableTemplate(readFile("../templates/table.html.mustache"));
    // 添加数据的页面路由
    CROW_ROUTE(app, "/")
    ([&indexTemplate]() {
        kainjow::mustache::data templateData;
        return crow::response(indexTemplate.render(templateData));
    });
    // 处理提交数据的路由
    CROW_ROUTE(app, "/submit")
    .methods("POST"_method)
    ([](const crow::request& req) {
        crow::json::rvalue json = crow::json::load(req.body);
        if (!json) {
            return crow::response(400);
        }
        std::string dataValue = json["data"].s();
        data.push_back(dataValue);

        return crow::response(200);
    });
    // 返回更新后的表格数据路由
    CROW_ROUTE(app, "/table")
    ([&tableTemplate]() {
        kainjow::mustache::data tableData;
        std::vector<kainjow::mustache::data> rows;
        for (const auto& item : data) {
            kainjow::mustache::data row;
            row.set("item", item);
            rows.push_back(row);
        }
        tableData.set("tableRows", rows);
        return crow::response(tableTemplate.render(tableData));
    });
    // 处理删除数据的路由
    CROW_ROUTE(app, "/delete")
    .methods("POST"_method)
    ([](const crow::request& req) {
        crow::json::rvalue json = crow::json::load(req.body);
        if (!json) {
            return crow::response(400);
        }
        std::string dataValue = json["data"].s();
        auto it = std::find(data.begin(), data.end(), dataValue);
        if (it != data.end()) {
            data.erase(it);
            return crow::response(200);
        } else {
            return crow::response(404);
        }
    });
    app.port(8080).multithreaded().run();
}

        启动程序:

        编译时间稍微有点长,主要是CMake写的太粗糙了。

        启动成功:

        打开浏览器,访问localhost:8080:

成功添加数据:

路由返回正常:


网站公告

今日签到

点亮在社区的每一天
去签到