pica/server/router.cpp

45 lines
1.5 KiB
C++

// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#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, Server* server) {
auto itr = table.find(path);
if (itr == table.end())
return handleNotFound(path, std::move(request));
try {
bool result = itr->second(request.get(), server);
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;
}