-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp-router.hpp
More file actions
85 lines (65 loc) · 2.2 KB
/
http-router.hpp
File metadata and controls
85 lines (65 loc) · 2.2 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
78
79
80
81
82
83
84
85
#ifndef _HTTP_ROUTER_HPP
#define _HTTP_ROUTER_HPP
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <csignal>
#include "utility.hpp"
#include "http-message.hpp"
#include "http-message-template.hpp"
#include <iostream>
#include <unordered_map>
#include <functional>
#include <initializer_list>
#include <thread>
#include <mutex>
#include <future>
#include <queue>
#include <atomic>
#include <exception>
#include <stdexcept>
#include <sstream>
using namespace util;
namespace http {
/*
package => request, handler func, socket descriptor
*/
using RouteFunc = std::function<RES(const REQ&)>;
using ReqPkg = pkg<REQ, RouteFunc, int>;
using RoutePkg = pkg<RouteFunc, std::vector<std::string>>;
class HttpRouter {
public:
HttpRouter(int maxWorker, std::string_view ip, uint16_t port) :
mMaxWorker(maxWorker), mIP(ip), mPort(port) {};
~HttpRouter() {stop();};
void start();
void stop();
void addRoute(std::string_view uri, RouteFunc func, std::vector<std::string> methods = {"get"});
bool isRunning() const {return mIsRunning;}
std::string_view getIP() const {return mIP;}
uint16_t getPort() const { return mPort;}
int getMaxWorker() const {return mMaxWorker;}
private:
void listenerProc(std::string_view ip, uint16_t port, std::promise<int> state);
void workerProc();
void pushReq(const ReqPkg& reqPkg);
inline void pushReq(REQ req, RouteFunc func, int sock) {pushReq(pack(req, func, sock));}
std::optional<ReqPkg> pullReq();
RouteFunc findRoute(std::string_view uri, std::string_view method);
private:
std::thread mListenerThread;
std::vector<std::thread> mWorkerThread;
std::condition_variable mWorkerCondvar;
std::mutex mReqMutex;
std::queue<ReqPkg> mReqQ;
std::mutex mReqQMutex;
std::unordered_map<std::string, RoutePkg> mRouteMap;
std::mutex mRouteMutex;
bool mIsRunning;
int mServSock = -1;
int mMaxWorker;
std::string mIP;
uint16_t mPort;
};
}
#endif