-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.h
More file actions
47 lines (37 loc) · 1.09 KB
/
router.h
File metadata and controls
47 lines (37 loc) · 1.09 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
#pragma once
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>
#include "request.h"
#include "response.h"
class Router {
public:
using Handler = std::function<Response(const Request &)>;
void add(std::string method, std::string path, Handler h) {
routes_[method + " " + path] = std::move(h);
}
Response handle(const Request &req) const {
std::string_view route_path = req.path;
if (auto q = route_path.find('?'); q != std::string_view::npos)
route_path = route_path.substr(0, q);
std::string key;
key.reserve(req.method.size() + 1 + route_path.size());
key.append(req.method);
key.push_back(' ');
key.append(route_path);
if (auto it = routes_.find(key); it != routes_.end())
return it->second(req);
return not_found(req);
}
private:
std::unordered_map<std::string, Handler> routes_;
static Response not_found(const Request &) {
Response r;
r.status_code = 404;
r.status_text = "Not Found";
r.body = "404 Not Found\n";
r.headers["Content-Type"] = "text/plain";
return r;
}
};