Slim Framework v3 - 与 AND 相同的路线,但没有最后的 '/'

SlimFramework v3 - Same route with AND whithout final '/'

我用 SlimFramework v3 创建了一个小应用程序,我可以像这样构建一个简单的路由:

// GET localhost/admin
$app->get('/admin', function(){
    # code here
});

我的问题是这只适用于 localhost/admin 而不适用于 localhost/admin/(最终反斜杠)。是否可以选择对两者都使用 ONE 路由?

有2种可能

  1. 指定一个可选的/

    $app->get('/admin[/]', function(){
        # code here
    });
    
  2. 添加中间件,将以 / 结尾的路由重定向到没有 url 的路由。

    use Psr\Http\Message\RequestInterface as Request;
    use Psr\Http\Message\ResponseInterface as Response;
    
    $app->add(function (Request $request, Response $response, callable $next) {
        $uri = $request->getUri();
        $path = $uri->getPath();
        if ($path != '/' && substr($path, -1) == '/') {
            // permanently redirect paths with a trailing slash
            // to their non-trailing counterpart
            $uri = $uri->withPath(substr($path, 0, -1));
    
            if($request->getMethod() == 'GET') {
                return $response->withRedirect((string)$uri, 301);
            }
            else {
                return $next($request->withUri($uri), $response);
            }
        }
    
        return $next($request, $response);
    });
    

    (来源:http://www.slimframework.com/docs/cookbook/route-patterns.html