Add logic to handle root node lookups

This commit is contained in:
Sky Johnson 2024-09-19 12:35:16 -05:00
parent 12ddd83cbd
commit b5f94930dc
2 changed files with 23 additions and 0 deletions

View File

@ -36,6 +36,13 @@ class SegmentRouter implements Router
// params will hold any dynamic segments we find
$params = [];
// if the URI is just a slash, we can return the handler for the root node
if ($uri === '/') {
return isset($node[$method])
? ['code' => 200, 'handler' => $node[$method], 'params' => null]
: ['code' => 405];
}
// We'll split up the URI into segments and traverse the node tree
foreach (explode('/', trim($uri, '/')) as $segment) {
// if there is a node for this segment, move to it

View File

@ -90,6 +90,22 @@ for ($i = 0; $i < 10; $i++) {
$res['handler'](...$res['params']);
}
$r->clear();
echoTitle('Testing root node');
$r->add('GET', '/', function() {
echo "Root node is gtg!\n";
});
$res = $r->lookup('GET', '/');
if ($res['code'] !== 200) {
echo "Failed to handle request for /\n";
exit(1);
}
$res['handler']();
echo "\n".Color::blue("✔️ Done!")."\n\n";
function echoTitle(string $title) {
echo "\n";
echo Color::bold(Color::black("===============================================================")) . "\n";