forked from heapwolf/redirector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.cc
67 lines (48 loc) · 1.19 KB
/
server.cc
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
#include "redirector.h"
using namespace redirector;
int main() {
leveldb::Options options;
options.create_if_missing = true;
string path = "./db";
leveldb::Status status = leveldb::DB::Open(options, path, &db);
if (!status.ok()) {
cout << "Coun't open LevelDB" << endl;
return 1;
}
Route router;
Debug debug("server", Debug::verbose, cout);
Server server([&](auto &req, auto &res) {
auto u = uri::ParseHttpUrl(req.url);
auto match = router.set(u.path);
//
// CREATE SHORT URL
//
if (match.test("/shorten")) {
string id = put(u.query["url"]);
int status = id.length() > 0 ? 200 : 500;
res.setStatus(200);
res.setHeader("Content-Type", "text/plain");
res.setHeader("Connection", "keep-alive");
res.end(id);
return;
}
//
// REDIRECT A URL
//
else if (match.test("/:id")) {
string r = get(match.get("id"));
if (r.length() > 0) {
res.setStatus(301, "Moved Permanently");
res.setHeader("Location", r);
res.end();
return;
}
}
//
// NOT FOUND
//
res.setStatus(404);
res.end();
});
server.listen("0.0.0.0", 8000);
}