2025-03-08 20:55:07 +01:00

135 lines
2.3 KiB
C++

#include <seafire/routing/route.hxx>
#include <stdexcept>
namespace seafire::routing
{
static
void
ensure_valid_path(std::string const& path)
{
if (!path.empty()) {
if (path.front() == '/') {
throw std::invalid_argument{"route path must not start with '/'"};
}
if (path.back() == '/') {
throw std::invalid_argument{"route path must not end with '/'"};
}
}
}
route_t::
route_t() = default;
route_t::
route_t(std::string path)
: path_{std::move(path)}
{
ensure_valid_path(path_);
}
route_t::
route_t(std::string path, server::request_handler_t handler)
: path_{std::move(path)}, handler_{std::move(handler)}
{
ensure_valid_path(path_);
}
std::string const&
route_t::
path() const
{
return path_;
}
std::vector<server::middleware_t> const&
route_t::
middleware() const
{
return middleware_;
}
std::optional<server::request_handler_t> const&
route_t::
handler() const
{
return handler_;
}
std::list<route_t> const&
route_t::
children() const
{
return children_;
}
void
route_t::
use(server::middleware_t m)
{
middleware_.emplace_back(std::move(m));
}
route_t&
route_t::
add_route()
{
children_.emplace_back();
return children_.back();
}
route_t&
route_t::
add_route(route_t r)
{
children_.emplace_back(std::move(r));
return children_.back();
}
route_t&
route_t::
add_route(std::string path)
{
return add_route(route_t{std::move(path)});
}
route_t&
route_t::
add_route(std::string path, server::request_handler_t handler)
{
return add_route(route_t{std::move(path), std::move(handler)});
}
std::ostream&
to_stream(std::ostream& o, route_t const& r, std::size_t indent)
{
o << std::string(indent, ' ');
o << " -> '" << (r.path().empty() ? "<empty>" : r.path()) << '\'';
if (!r.middleware().empty()) {
o << " (with middleware)";
}
if (!r.handler()) {
o << " (null handler)";
}
o << '\n';
for (auto const& child : r.children()) {
to_stream(o, child, indent + 2);
}
return o;
}
std::ostream&
operator<<(std::ostream& o, route_t const& route)
{
return to_stream(o, route, 0);
}
} // namespace seafire::routing