-
Notifications
You must be signed in to change notification settings - Fork 16
/
multiple_handlers.cpp
75 lines (59 loc) · 2.05 KB
/
multiple_handlers.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
#include "expresscpp/console.hpp"
#include "expresscpp/expresscpp.hpp"
using namespace expresscpp;
int main() {
ExpressCpp app;
struct User {
std::string name;
uint8_t age;
int id;
};
std::vector<User> users{{"john", 0, 30}, {"steve", 1, 40}};
auto authenticateUser = [&](auto req, auto res, auto next) {
auto headers = req->getHeaders();
if ((headers.find("Authorization") != headers.end())) {
next();
} else {
res->SetStatus(401);
res->Send(R"({"error":"not allowed"})");
}
};
auto authenticateMachine = [&](auto req, auto res, auto next) {
auto headers = req->getHeaders();
if ((headers.find("Authorization") != headers.end())) {
next();
} else {
res->SetStatus(401);
res->Send(R"({"error":"not allowed"})");
}
};
auto serverUser = [&](auto req, auto res, auto /*next*/) {
auto params = req->GetParams();
if ((params.find("userId") != params.end())) {
auto id = params.at("userId");
const int userId = std::stoi(id);
// ops, possible the user does not exist -> exception
auto user = users.at(userId);
res->Json(fmt::format("{{\"name\":\"{}\", \"id\":\"{}\", \"age\":{}}}", user.name, user.id, user.age));
} else {
res->SetStatus(404);
res->Send(R"({"error":"user not found"})");
}
};
app.Get("/users/:userId", authenticateUser, serverUser);
app.Get("/things/:userId", authenticateUser, authenticateMachine, serverUser);
constexpr uint16_t port = 8081;
app.Listen(port,
[=](auto ec) {
if (ec) {
std::cerr << "ERROR: " << ec.message() << std::endl;
std::cerr << "exiting..." << std::endl;
exit(1);
}
std::cout << fmt::format(R"(you can try now (should work): "curl http://localhost:{}/users/0")", port)
<< std::endl;
std::cout << fmt::format(R"(and (should fail): "curl http://localhost:{}/users/10")", port) << std::endl;
})
.Run();
return 0;
}