42 lines
1.4 KiB
C++
42 lines
1.4 KiB
C++
|
#include "router.h"
|
||
|
|
||
|
Router::Router():
|
||
|
table()
|
||
|
{
|
||
|
|
||
|
}
|
||
|
|
||
|
void Router::addRoute(const std::string& path, const Handler& handler) {
|
||
|
auto result = table.emplace(path, handler);
|
||
|
if (!result.second)
|
||
|
std::cerr << "could'not add route " + path + " to the routing table";
|
||
|
}
|
||
|
|
||
|
void Router::route(const std::string& path, std::unique_ptr<Request> request) {
|
||
|
auto itr = table.find(path);
|
||
|
if (itr == table.end())
|
||
|
return handleNotFound(path, std::move(request));
|
||
|
|
||
|
try {
|
||
|
bool result = itr->second(request.get());
|
||
|
if (!result)
|
||
|
handleInternalError(std::runtime_error("handler failed to handle the request"), std::move(request));
|
||
|
} catch (const std::exception& e) {
|
||
|
handleInternalError(e, std::move(request));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void Router::handleNotFound(const std::string& path, std::unique_ptr<Request> request) {
|
||
|
Response notFound(Response::Status::notFound);
|
||
|
notFound.setBody(std::string("Path \"") + path + "\" was not found");
|
||
|
notFound.replyTo(*request.get());
|
||
|
std::cerr << "Not found: " << path << std::endl;
|
||
|
}
|
||
|
|
||
|
void Router::handleInternalError(const std::exception& exception, std::unique_ptr<Request> request) {
|
||
|
Response error(Response::Status::internalError);
|
||
|
error.setBody(std::string(exception.what()));
|
||
|
error.replyTo(*request.get());
|
||
|
std::cerr << "Internal error: " << exception.what() << std::endl;
|
||
|
}
|