amphp / http-server-router
Router responder for Amp's HTTP server.
Fund package maintenance!
amphp
Installs: 191 391
Dependents: 23
Suggesters: 0
Security: 0
Stars: 35
Watchers: 8
Forks: 5
Open Issues: 3
Requires
- php: >=8.1
- amphp/cache: ^2
- amphp/http: ^2-dev
- amphp/http-server: ^3
- amphp/socket: ^2
- nikic/fast-route: ^1
Requires (Dev)
- amphp/log: ^2
- amphp/php-cs-fixer-config: ^2
- amphp/phpunit-util: ^3
- league/uri: ^6
- phpunit/phpunit: ^9
- psalm/phar: ^5.6
This package is auto-updated.
Last update: 2023-05-27 03:13:27 UTC
README
This package provides a routing RequestHandler
for Amp's HTTP server based on the request URI and method based on FastRoute.
Installation
This package can be installed as a Composer dependency.
composer require amphp/http-server-router
Usage
Router
implements RequestHandler
. Any attached RequestHandler
and Middleware
instances will receive any ServerObserver
events.
Routes can be defined using the addRoute($method, $uri, $requestHandler)
method. Please read the FastRoute documentation on how to define placeholders.
Matched route arguments are available in the request attributes under the Amp\Http\Server\Router
key as an associative array.
Example
$router = new Router; $router->addRoute('GET', '/', new CallableRequestHandler(function () { return new Response(HttpStatus::OK, ['content-type' => 'text/plain'], 'Hello, world!'); })); $router->addRoute('GET', '/{name}', new CallableRequestHandler(function (Request $request) { $args = $request->getAttribute(Router::class); return new Response(HttpStatus::OK, ['content-type' => 'text/plain'], "Hello, {$args['name']}!"); }));
Limitations
The Router
will decode the URI path before matching.
This will also decode any forward slashes (/
), which might result in unexpected matching for URIs with encoded slashes.
FastRoute placeholders match path segments by default, which are separated by slashes.
That means a route like /token/{token}
won't match if the token contains an encoded slash.
You can work around this limitation by using a custom regular expression for the placeholder like /token/{token:.+}
.