#ifndef HTTPSERVER_HPP #define HTTPSERVER_HPP #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace beast = boost::beast; namespace http = beast::http; namespace asio = boost::asio; using tcp = boost::asio::ip::tcp; namespace pmc { namespace net { /** * @brief HTTP请求处理器类型定义 * * 处理HTTP请求并返回响应 */ using HttpRequestHandler = std::function( const http::request&, const std::unordered_map&)>; /** * @brief 中间件处理器类型定义 * * 用于处理请求链的中间件 */ using MiddlewareHandler = std::function&, http::response&, const std::unordered_map&)>; /** * @brief HTTP服务器类(合并增强版) * * 基于boost::asio和boost::beast的异步HTTP服务器 * 结合了原始版本的易用性和修复版本的功能完整性 */ class HttpServer { public: /** * @brief 构造函数(监听所有接口) * @param port 监听端口 * @param threads 工作线程数 */ explicit HttpServer(unsigned short port, unsigned int threads = 1); /** * @brief 构造函数(指定监听地址) * @param address 监听IP地址(如 "0.0.0.0" 或 "127.0.0.1") * @param port 监听端口 * @param threads 工作线程数 */ explicit HttpServer(const std::string& address, unsigned short port, unsigned int threads = 1); /** * @brief 析构函数 */ ~HttpServer(); /** * @brief 启动服务器 */ void start(); /** * @brief 停止服务器 */ void stop(); /** * @brief 注册GET请求处理器 * @param path 请求路径 * @param handler 请求处理器 */ void get(const std::string& path, HttpRequestHandler handler); /** * @brief 注册POST请求处理器 * @param path 请求路径 * @param handler 请求处理器 */ void post(const std::string& path, HttpRequestHandler handler); /** * @brief 注册PUT请求处理器 * @param path 请求路径 * @param handler 请求处理器 */ void put(const std::string& path, HttpRequestHandler handler); /** * @brief 注册DELETE请求处理器 * @param path 请求路径 * @param handler 请求处理器 */ void del(const std::string& path, HttpRequestHandler handler); /** * @brief 注册中间件 * @param middleware 中间件处理器 */ void use(MiddlewareHandler middleware); /** * @brief 设置静态文件目录 * @param path 静态文件目录路径 */ void setStaticDirectory(const std::string& path); /** * @brief 获取服务器状态 * @return 服务器是否正在运行 */ bool isRunning() const; /** * @brief 获取服务器端口 * @return 服务器监听端口 */ unsigned short getPort() const; /** * @brief 获取服务器监听地址 * @return 服务器监听地址 */ std::string getAddress() const; /** * @brief 运行服务器(阻塞调用)- 从原始版本继承 */ void run(); /** * @brief 显示服务器状态信息 - 从原始版本继承 */ void showStatus() const; private: // 内部类声明 class Session; class Listener; // 服务器配置 std::string address_; unsigned short port_; unsigned int threads_; std::atomic running_{false}; // Boost.Asio上下文 std::unique_ptr ioc_; // 网络组件 std::shared_ptr listener_; std::vector worker_threads_; // 路由表 std::unordered_map get_handlers_; std::unordered_map post_handlers_; std::unordered_map put_handlers_; std::unordered_map delete_handlers_; // 中间件链 std::vector middlewares_; // 静态文件目录 std::string static_directory_; // 内部方法 std::unordered_map parseQueryParams(const std::string& query); // 请求处理 http::response handleRequest(const http::request& req); }; } // namespace net } // namespace pmc #endif // HTTPSERVER_HPP