-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest_handler.cc
More file actions
77 lines (70 loc) · 1.86 KB
/
request_handler.cc
File metadata and controls
77 lines (70 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "request_handler.h"
#include <fmt/core.h>
#include "http_request.h"
#include "http_response.h"
#include "inner/filesystem.hpp"
using namespace ghc::filesystem;
void RequestHandler(const http::Request &req, http::Response &rsp)
{
auto const &filename = req.query();
if (filename.empty())
{
ResponseFilesLink(rsp);
return;
}
ResponseFile(filename, rsp);
}
std::vector<std::string> getAllFilenamesByBaseDir(std::string const &targetDir)
{
std::vector<std::string> ret;
for (const auto &entry : directory_iterator(targetDir))
{
if (!is_directory(entry))
{
ret.push_back(entry.path().filename().string());
}
}
return ret;
}
void ResponseFilesLink(http::Response &rsp)
{
std::string links;
for (auto &&filename : getAllFilenamesByBaseDir(current_path().string()))
{
links.append(
fmt::format(R"(<li><a href="/?{}">{}</a></li>)", filename, filename));
}
rsp.body() = fmt::format(
R"(<html><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><ul>{}</ul></html>)",
links);
rsp.responseOk();
}
void ResponseFile(const std::string &filename, http::Response &rsp)
{
auto filePath = current_path();
filePath /= filename;
if (!exists(filePath))
{
rsp.body() = R"(
<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<head>
<title>HTTP 400 错误:请求无效</title>
</head>
<body>
<h1>HTTP 400 错误:请求无效</h1>
<p>很抱歉,您的请求无效。请检查您的请求是否正确。</p>
</body>
</html>)";
rsp.responseBad();
return;
}
rsp.fileinfo() = http::fileinfo{
file_size(filePath),
filePath.string(),
};
rsp.setContentType("application/octet-stream");
rsp.headers()["Content-Disposition"] =
fmt::format(R"(attachment; filename="{}")", filename);
rsp.responseOk();
}