VWeb/Includes/Router.h

63 lines
1.8 KiB
C
Raw Normal View History

#pragma once
#include "Route.h"
#include <functional>
#include <memory>
namespace VWeb {
typedef std::function<bool(Request &, Response &)> RouteFunction;
2024-02-04 13:52:08 +01:00
typedef std::function<std::shared_ptr<Route>()> RouteInstaniateFunction;
struct RouteTree {
void Add(const std::string &path, uint32_t allowedMethods,
RouteInstaniateFunction instaniate);
Ref<Route> Find(const std::string &path, Request &request);
protected:
struct Node {
explicit Node(const uint64_t id) : ID(id) {}
std::unordered_map<std::string, std::unique_ptr<Node>> Children{};
uint64_t ID{0};
};
Node Root{0};
uint64_t m_NodeID = 1;
struct RouteInstance {
uint32_t AllowedMethods = HttpMethod::OPTIONS | HttpMethod::HEAD;
RouteInstaniateFunction Instaniate;
};
std::unordered_map<uint64_t, RouteInstance> m_Routes;
};
class Router {
public:
Router();
Ref<Response> HandleRoute(Ref<Request> &request);
Ref<Route> FindRoute(Ref<Request> &request);
2024-02-04 13:52:08 +01:00
template <typename T>
void Register(const std::string &endpoint, HttpMethod allowedMethod) {
Register<T>(endpoint, static_cast<uint32_t>(allowedMethod));
}
template <typename T>
void
Register(const std::string &endpoint,
uint32_t allowedMethods = static_cast<uint32_t>(HttpMethod::ALL)) {
static_assert(std::is_base_of_v<Route, T>, "must be a Route");
m_Tree.Add(endpoint,
allowedMethods | HttpMethod::HEAD | HttpMethod::OPTIONS,
[] { return std::make_shared<T>(); });
2024-02-04 13:52:08 +01:00
}
void Get(const std::string &path, const RouteFunction &);
void Post(const std::string &path, const RouteFunction &);
void Put(const std::string &path, const RouteFunction &);
void Patch(const std::string &path, const RouteFunction &);
void Delete(const std::string &path, const RouteFunction &);
2024-02-04 13:52:08 +01:00
private:
RouteTree m_Tree{};
};
} // namespace VWeb