|
| 1 | +/* |
| 2 | + * .============. |
| 3 | + * // M A K E / \ |
| 4 | + * // C++ DEV / \ |
| 5 | + * // E A S Y / \/ \ |
| 6 | + * ++ ----------. \/\ . |
| 7 | + * \\ \ \ /\ / |
| 8 | + * \\ \ \ / |
| 9 | + * \\ \ \ / |
| 10 | + * -============' |
| 11 | + * |
| 12 | + * Copyright (c) 2025 Hevake and contributors, all rights reserved. |
| 13 | + * |
| 14 | + * This file is part of cpp-tbox (https://github.com/cpp-main/cpp-tbox) |
| 15 | + * Use of this source code is governed by MIT license that can be found |
| 16 | + * in the LICENSE file in the root of the source tree. All contributing |
| 17 | + * project authors may be found in the CONTRIBUTORS.md file in the root |
| 18 | + * of the source tree. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * 文件下载服务器示例 |
| 23 | + * |
| 24 | + * 这个示例展示了如何使用 FileDownloaderMiddleware 实现文件下载功能 |
| 25 | + * 包含目录浏览和文件下载功能 |
| 26 | + */ |
| 27 | + |
| 28 | +#include <signal.h> |
| 29 | +#include <iostream> |
| 30 | +#include <filesystem> |
| 31 | +#include <tbox/base/log.h> |
| 32 | +#include <tbox/base/log_output.h> |
| 33 | +#include <tbox/base/scope_exit.hpp> |
| 34 | +#include <tbox/event/signal_event.h> |
| 35 | +#include <tbox/event/loop.h> |
| 36 | +#include <tbox/network/sockaddr.h> |
| 37 | +#include <tbox/http/server/server.h> |
| 38 | +#include <tbox/http/server/middlewares/router_middleware.h> |
| 39 | +#include <tbox/http/server/middlewares/file_downloader_middleware.h> |
| 40 | +#include <tbox/util/fs.h> |
| 41 | +#include <tbox/trace/sink.h> |
| 42 | + |
| 43 | +using namespace std; |
| 44 | +using namespace tbox; |
| 45 | +using namespace tbox::event; |
| 46 | +using namespace tbox::network; |
| 47 | +using namespace tbox::http; |
| 48 | +using namespace tbox::http::server; |
| 49 | + |
| 50 | +// 文件下载服务器状态页面 |
| 51 | +const char *kStatusHtml = R"( |
| 52 | +<!DOCTYPE html> |
| 53 | +<html> |
| 54 | +<head> |
| 55 | + <meta charset="UTF-8"> |
| 56 | + <title>文件下载服务器</title> |
| 57 | + <style> |
| 58 | + body { font-family: Arial, sans-serif; margin: 20px; } |
| 59 | + h1 { color: #333; } |
| 60 | + .status { border: 1px solid #ddd; padding: 20px; border-radius: 5px; max-width: 500px; } |
| 61 | + .info { margin-bottom: 10px; } |
| 62 | + .label { font-weight: bold; } |
| 63 | + .good { color: #4CAF50; } |
| 64 | + .links { margin-top: 20px; } |
| 65 | + .links a { color: #4CAF50; text-decoration: none; margin-right: 15px; } |
| 66 | + </style> |
| 67 | +</head> |
| 68 | +<body> |
| 69 | + <h1>文件下载服务器</h1> |
| 70 | + <div class="status"> |
| 71 | + <div class="info"><span class="label">状态:</span> <span class="good">运行中</span></div> |
| 72 | + <div class="info"><span class="label">版本:</span> 1.0.0</div> |
| 73 | + <div class="info"><span class="label">目录浏览:</span> 已启用</div> |
| 74 | + </div> |
| 75 | + <div class="links"> |
| 76 | + <a href="/">浏览文件</a> |
| 77 | + <a href="/api/status">API状态</a> |
| 78 | + </div> |
| 79 | +</body> |
| 80 | +</html> |
| 81 | +)"; |
| 82 | + |
| 83 | +int main(int argc, char **argv) |
| 84 | +{ |
| 85 | + std::string serve_dir = "./"; |
| 86 | + std::string bind_addr = "0.0.0.0:8080"; |
| 87 | + |
| 88 | + // 处理命令行参数 |
| 89 | + if (argc >= 2) |
| 90 | + serve_dir = argv[1]; |
| 91 | + |
| 92 | + if (argc >= 3) |
| 93 | + bind_addr = argv[2]; |
| 94 | + |
| 95 | + // 启用日志输出 |
| 96 | + LogOutput_Enable(); |
| 97 | + LogInfo("Starting file download server"); |
| 98 | + |
| 99 | +#if 0 //! 要监控性能时,打开 |
| 100 | + auto &trace_sink = tbox::trace::Sink::GetInstance(); |
| 101 | + trace_sink.setPathPrefix("/tmp/file_download/trace"); |
| 102 | + trace_sink.enable(); |
| 103 | +#endif |
| 104 | + |
| 105 | + // 检查目录是否存在 |
| 106 | + if (!tbox::util::fs::IsDirectoryExist(serve_dir)) { |
| 107 | + LogErr("Directory '%s' doesn't exist or is not a directory", serve_dir.c_str()); |
| 108 | + return 1; |
| 109 | + } |
| 110 | + |
| 111 | + // 创建事件循环和信号处理 |
| 112 | + auto sp_loop = Loop::New(); |
| 113 | + auto sp_sig_event = sp_loop->newSignalEvent(); |
| 114 | + |
| 115 | + // 确保资源被正确释放 |
| 116 | + SetScopeExitAction( |
| 117 | + [=] { |
| 118 | + delete sp_sig_event; |
| 119 | + delete sp_loop; |
| 120 | + } |
| 121 | + ); |
| 122 | + |
| 123 | + // 初始化信号处理 |
| 124 | + sp_sig_event->initialize({SIGINT, SIGTERM}, Event::Mode::kPersist); |
| 125 | + sp_sig_event->enable(); |
| 126 | + |
| 127 | + // 创建HTTP服务器 |
| 128 | + Server srv(sp_loop); |
| 129 | + if (!srv.initialize(SockAddr::FromString(bind_addr), 5)) { |
| 130 | + LogErr("HTTP server initialization failed"); |
| 131 | + return 1; |
| 132 | + } |
| 133 | + |
| 134 | + srv.start(); |
| 135 | + //srv.setContextLogEnable(true); //! 调试时需要看详细收发数据时可以打开 |
| 136 | + |
| 137 | + // 创建路由器和文件下载中间件 |
| 138 | + RouterMiddleware router; |
| 139 | + FileDownloaderMiddleware file_downloader(sp_loop); |
| 140 | + |
| 141 | + // 添加状态页面路由 |
| 142 | + router.get("/api/status", [](ContextSptr ctx, const NextFunc& next) { |
| 143 | + ctx->res().status_code = StatusCode::k200_OK; |
| 144 | + ctx->res().headers["Content-Type"] = "application/json"; |
| 145 | + ctx->res().body = R"({"status":"running","version":"1.0.0"})"; |
| 146 | + }); |
| 147 | + |
| 148 | + router.get("/status", [](ContextSptr ctx, const NextFunc& next) { |
| 149 | + ctx->res().status_code = StatusCode::k200_OK; |
| 150 | + ctx->res().headers["Content-Type"] = "text/html; charset=UTF-8"; |
| 151 | + ctx->res().body = kStatusHtml; |
| 152 | + }); |
| 153 | + |
| 154 | + // 配置文件下载中间件 |
| 155 | + if (!file_downloader.addDirectory("/", serve_dir)) { |
| 156 | + LogErr("Failed to add directory: %s", serve_dir.c_str()); |
| 157 | + return 1; |
| 158 | + } |
| 159 | + |
| 160 | + // 启用目录浏览功能 |
| 161 | + file_downloader.setDirectoryListingEnabled(true); |
| 162 | + |
| 163 | + // 添加常见的 MIME 类型映射(如果需要额外的映射) |
| 164 | + // file_downloader.setMimeType("pdf", "application/pdf"); |
| 165 | + |
| 166 | + // 添加中间件到服务器 |
| 167 | + srv.use(&router); |
| 168 | + srv.use(&file_downloader); |
| 169 | + |
| 170 | + // 设置信号处理回调 |
| 171 | + sp_sig_event->setCallback( |
| 172 | + [&] (int sig) { |
| 173 | + LogInfo("Received signal %d, preparing to exit...", sig); |
| 174 | + srv.stop(); |
| 175 | + sp_loop->exitLoop(); |
| 176 | + } |
| 177 | + ); |
| 178 | + |
| 179 | + LogInfo("File download server started, listening on http://%s/, serving directory: %s", |
| 180 | + bind_addr.c_str(), serve_dir.c_str()); |
| 181 | + |
| 182 | + // 运行事件循环 |
| 183 | + sp_loop->runLoop(); |
| 184 | + |
| 185 | + LogInfo("Server stopped"); |
| 186 | + srv.cleanup(); |
| 187 | + |
| 188 | + LogInfo("Exiting"); |
| 189 | + return 0; |
| 190 | +} |
0 commit comments