-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
92 lines (83 loc) · 2.32 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
85
86
87
88
89
90
91
92
#include <string>
#include <functional>
#include <map>
class Router{
private:
std::map<std::string,std::function<void(std::string)>> get_routes;
std::map<std::string,std::function<void(std::string)>> post_routes;
public:
Router() = default;
Router(const Router&) = delete;
Router(const Router&&) = delete;
Router& operator = (const Router&) = delete;
Router& operator = (const Router&&) = delete;
template<typename Url,typename Callback>
void get(const Url& url,const Callback& callback)
{
get_routes[url] = callback;
}
template<typename Url,typename Callback>
void post(const Url& url,const Callback& callback)
{
post_routes[url] = callback;
}
void mapGetRoutes(const char* url)
{
for(std::map<std::string,std::function<void(std::string)>>::iterator it= get_routes.begin(); it!=get_routes.end();it++)
{
if(it->first == url){
std::invoke(it->second,it->first);
}
}
}
void mapPostRoutes(const char* url)
{
for(std::map<std::string,std::function<void(std::string)>>::iterator it= post_routes.begin(); it!=post_routes.end();it++)
{
if(it->first == url){
std::invoke(it->second,it->first);
}
}
}
bool routeExists(const char*url)
{
for(std::map<std::string,std::function<void(std::string)>>::iterator it= post_routes.begin(); it!=post_routes.end();it++)
{
if(it->first == url){
return true;
}
}
for(std::map<std::string,std::function<void(std::string)>>::iterator it= get_routes.begin(); it!=get_routes.end();it++)
{
if(it->first == url){
return true;
}
}
return false;
}
void dispatch(const char* url)
{
if(routeExists(url))
{
mapGetRoutes(url);
mapPostRoutes(url);
}else
{
throw std::runtime_error(std::string("Route not found --- ").append(url));
}
}
}router;
struct HomeController{
void getUserHome(){}
void login(){}
}homeController;
int main([[maybe_unused]] int argc,[[maybe_unused]]const char* argv[])
{
router.get("/home",[&]([[maybe_unused]]std::string url){
return std::invoke(&HomeController::getUserHome,homeController);
});
router.post("/login",[&]([[maybe_unused]]std::string url){
return std::invoke(&HomeController::login,homeController);
});
router.dispatch(argv[1]);
}