63 lines
1.8 KiB
C++
63 lines
1.8 KiB
C++
#pragma once
|
|
|
|
#include "Route.h"
|
|
|
|
#include <functional>
|
|
#include <memory>
|
|
|
|
namespace VWeb {
|
|
typedef std::function<bool(Request &, Response &)> RouteFunction;
|
|
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);
|
|
|
|
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>(); });
|
|
}
|
|
|
|
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 &);
|
|
|
|
private:
|
|
RouteTree m_Tree{};
|
|
};
|
|
} // namespace VWeb
|