-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
84 lines (73 loc) · 2.87 KB
/
main.cpp
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
78
79
80
81
82
83
84
/***********************
* @file: main.cpp
* @author: shizuku
* @date: 2020/7/15
***********************/
#include <iostream>
#include <iomanip>
#include "server_config.h"
#include "http/server.h"
#include "server_router.h"
#include "cache_file_pool.h"
#include "server_proxy_passer.h"
server_config *sc;
server_router *router;
server_proxy_passer *passer;
cache_file_pool *file_pool;
void www(const http::request &req, http::response res) {
std::cout << req.method << "\t" << req.url << std::endl;
if (!passer->pass(req, res)) {
auto t = std::time(nullptr);
std::stringstream tt{};
tt << std::put_time(std::gmtime(&t), "%c %Z");
auto time = tt.str();
try {
auto path = router->route(req.url);
auto s = file_pool->get(path);
res.write_head(200, "OK", http::response_headers{std::map<std::string, std::string>{
{"Date", time},
{"Accept-Ranges", "bytes"},
{"Content-Type", s.mime_type},
{"Content-Length", std::to_string(s.length)},
{"Server", "shizuku/0.1"},
}});
res.write(s.content, s.length);
} catch (const http::not_found &e) {
auto s = file_pool->get(sc->error_pages["404"]);
res.write_head(404, "Not Found", http::response_headers{std::map<std::string, std::string>{
{"Date", time},
{"Accept-Ranges", "bytes"},
{"Content-Type", s.mime_type},
{"Content-Length", std::to_string(s.length)},
{"Server", "shizuku/0.1"},
}});
res.write(s.content, s.length);
} catch (const http::forbidden &e) {
auto s = file_pool->get(sc->error_pages["403"]);
res.write_head(403, "Forbidden", http::response_headers{std::map<std::string, std::string>{
{"Date", time},
{"Accept-Ranges", "bytes"},
{"Content-Type", s.mime_type},
{"Content-Length", std::to_string(s.length)},
{"Server", "shizuku/0.1"},
}});
res.write(s.content, s.length);
}
res.shutdown();
}
}
int main() {
signal(SIGPIPE, SIG_IGN);
const std::string config_filename = "config.json";
sc = new server_config(config_filename);
router = new server_router(static_cast<std::map<std::string, std::string, cmp> &&>(sc->router));
passer = new server_proxy_passer(
static_cast<std::map<std::string, std::map<std::string, std::string>, cmp> &&>(sc->proxy_pass));
file_pool = new cache_file_pool{sc->expires};
http::create_server(&www).listen(sc->port);
delete sc;
delete router;
delete passer;
delete file_pool;
return 0;
}