【发布时间】:2022-09-26 11:18:54
【问题描述】:
我正在使用 uWebSockets 库在 C++ 中设置 HTTP 服务器,并且我想添加一个中间件来提供静态文件,类似于 app.use(express.static(path.join(__dirname, \'public\'))); 在 Express.js 中所做的。
静态文件位于public 文件夹中。中间件应该使服务器加载路径http://localhost:8087/css/bootstrap.min.css下的文件,而不是http://localhost:8087/public/css/bootstrap.min.css,从而将root重新路由到public。
如何使用 uWebSockets 库在 C++ 中做到这一点?我已经检查了uWS::App 结构,但是我发现没有与路径或提供静态文件相关的任何内容。
这是一个 HTTP 服务器的示例:
#include <uWebSockets/App.h>
#include <rapidjson/rapidjson.h>
#include \"util/AsyncFileReader.h\"
#include \"util/AsyncFileStreamer.h\"
#include <iostream>
#include <string>
void get_home(uWS::HttpResponse<false> *res, uWS::HttpRequest *req) {
res->writeHeader(\"Content-Type\", \"text/html; charset=utf8\");
// res->writeStatus(uWS::HTTP_200_OK);
// res->end(\"Hello! This is <b>Sergei\'s C++ web server</b>.\");
AsyncFileReader page_contents(\"./public/home.html\");
res->end(page_contents.peek(0));
}
int main() {
int port{8087};
// HTTP
uWS::App app = uWS::App();
app.get(\"/\", get_home);
app.listen(port, [&port](auto *token) {
if (token) {
std::cout << \"Listening on port \" << port << std::endl;
}
})
.run();
return 0;
}
标签: c++ webserver httpserver uwebsockets