1
0
forked from blue/pica
pica/server/router.cpp

42 lines
1.4 KiB
C++
Raw Normal View History

2023-11-23 19:57:32 +00:00
#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";
}
2023-12-07 20:32:43 +00:00
void Router::route(const std::string& path, std::unique_ptr<Request> request, Server* server) {
2023-11-23 19:57:32 +00:00
auto itr = table.find(path);
if (itr == table.end())
return handleNotFound(path, std::move(request));
try {
2023-12-07 20:32:43 +00:00
bool result = itr->second(request.get(), server);
2023-11-23 19:57:32 +00:00
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;
}