diff --git a/src/SegmentRouter.php b/src/SegmentRouter.php index 1d61379..49cb5b1 100644 --- a/src/SegmentRouter.php +++ b/src/SegmentRouter.php @@ -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 diff --git a/tests/test.php b/tests/test.php index 25a24d6..52b2914 100644 --- a/tests/test.php +++ b/tests/test.php @@ -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";