Skip to content

Commit 5153ae2

Browse files
committed
Update docs
1 parent c5179df commit 5153ae2

File tree

2 files changed

+92
-16
lines changed

2 files changed

+92
-16
lines changed

README.md

Lines changed: 87 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# http-server-router
22

3-
This package provides a routing `RequestHandler` for [Amp's HTTP server](https://github.com/amphp/http-server) based on the request URI and method based on [FastRoute](https://github.com/nikic/FastRoute).
3+
This package provides a routing `RequestHandler` for [Amp's HTTP server](https://github.com/amphp/http-server) based on the request URI and method using [FastRoute](https://github.com/nikic/FastRoute).
44

55
## Installation
66

@@ -12,25 +12,93 @@ composer require amphp/http-server-router
1212

1313
## Usage
1414

15-
**`Router`** implements `RequestHandler`. Any attached `RequestHandler` and `Middleware` instances will receive any `ServerObserver` events.
15+
**`Router`** implements `RequestHandler`, which is used by an [`HttpServer`](https://github.com/amphp/http-server#creating-an-http-server) to handle incoming requests. Incoming requests are routed by `Router` to other `RequestHandler`s based on the request path.
1616

17-
Routes can be defined using the `addRoute($method, $uri, $requestHandler)` method. Please read the [FastRoute documentation on how to define placeholders](https://github.com/nikic/FastRoute#defining-routes).
17+
Routes can be defined using the `addRoute($method, $uri, $requestHandler, ...$middeware)` method.
18+
19+
```php
20+
public function addRoute(
21+
string $method,
22+
string $uri,
23+
RequestHandler $requestHandler,
24+
Middleware ...$middlewares,
25+
): void
26+
```
1827

1928
Matched route arguments are available in the request attributes under the `Amp\Http\Server\Router` key as an associative array.
2029

30+
Middleware provided to `addRoute()` will only be applied to the given route.
31+
32+
Please read the [FastRoute documentation on how to define placeholders](https://github.com/nikic/FastRoute#defining-routes).
33+
34+
### Middleware
35+
36+
In addition to specifying middlewares by route with `addRoute()`, you may wrap all routes with a common set of middlware using `stackMiddleware(...$middleware)`.
37+
38+
```php
39+
public function stackMiddleware(Middleware ...$middlewares): void
40+
```
41+
42+
### Fallback
43+
44+
If no routes match a request path, you can specify another instance of `RequestHandler` which will handle any unmatched routes. If no fallback handler is provided, a 404 response will be returned using the instance of `ErrorHandler` provided to the `Router` constructor.
45+
46+
```php
47+
public function setFallback(RequestHandler $requestHandler): void
48+
```
49+
2150
## Example
2251

2352
```php
24-
$router = new Router;
53+
use Amp\Http\HttpStatus;
54+
use Amp\Http\Server\DefaultErrorHandler;
55+
use Amp\Http\Server\Request;
56+
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
57+
use Amp\Http\Server\Response;
58+
use Amp\Http\Server\Router;
59+
use Amp\Http\Server\SocketHttpServer;
2560

26-
$router->addRoute('GET', '/', new CallableRequestHandler(function () {
27-
return new Response(HttpStatus::OK, ['content-type' => 'text/plain'], 'Hello, world!');
28-
}));
61+
// $logger is an instance of a PSR-3 logger.
62+
$server = SocketHttpServer::createForDirectAccess($logger);
63+
$errorHandler = new DefaultErrorHandler();
2964

30-
$router->addRoute('GET', '/{name}', new CallableRequestHandler(function (Request $request) {
31-
$args = $request->getAttribute(Router::class);
32-
return new Response(HttpStatus::OK, ['content-type' => 'text/plain'], "Hello, {$args['name']}!");
33-
}));
65+
$router = new Router($server, $errorHandler);
66+
67+
$router->addRoute('GET', '/', new ClosureRequestHandler(
68+
function () {
69+
return new Response(
70+
status: HttpStatus::OK,
71+
headers: ['content-type' => 'text/plain'],
72+
body: 'Hello, world!',
73+
);
74+
},
75+
));
76+
77+
$router->addRoute('GET', '/{name}', new ClosureRequestHandler(
78+
function (Request $request) {
79+
$args = $request->getAttribute(Router::class);
80+
return new Response(
81+
status: HttpStatus::OK,
82+
headers: ['content-type' => 'text/plain'],
83+
body: "Hello, {$args['name']}!",
84+
);
85+
},
86+
));
87+
88+
$server->expose('0.0.0.0:1337');
89+
90+
$server->start($router, $errorHandler);
91+
92+
// Serve requests until SIGINT or SIGTERM is received by the process.
93+
Amp\trapSignal([SIGINT, SIGTERM]);
94+
95+
$server->stop();
96+
```
97+
98+
A full example is found in [`examples/hello-world.php`](https://github.com/amphp/http-server-router/blob/2.x/examples/hello-world.php).
99+
100+
```bash
101+
php examples/hello-world.php
34102
```
35103

36104
## Limitations
@@ -40,3 +108,11 @@ This will also decode any forward slashes (`/`), which might result in unexpecte
40108
FastRoute placeholders match path segments by default, which are separated by slashes.
41109
That means a route like `/token/{token}` won't match if the token contains an encoded slash.
42110
You can work around this limitation by using a custom regular expression for the placeholder like `/token/{token:.+}`.
111+
112+
## Security
113+
114+
If you discover any security related issues, please use the private security issue reporter instead of using the public issue tracker.
115+
116+
## License
117+
118+
The MIT License (MIT). Please see [LICENSE](./LICENSE) for more information.

src/Router.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
1010
use FastRoute\Dispatcher;
1111
use FastRoute\RouteCollector;
12+
use function Amp\Http\Server\Middleware\stackMiddleware;
1213
use function FastRoute\simpleDispatcher;
1314

1415
final class Router implements RequestHandler
@@ -37,8 +38,6 @@ final class Router implements RequestHandler
3738

3839
/**
3940
* @param positive-int $cacheSize Maximum number of route matches to cache.
40-
*
41-
* @throws \Error If `$cacheSize` is less than zero.
4241
*/
4342
public function __construct(
4443
HttpServer $httpServer,
@@ -213,7 +212,7 @@ public function addRoute(
213212
* All middlewares are called in the order they're passed, so the first middleware is the outer middleware.
214213
*
215214
* On repeated calls, the later call will wrap the passed middlewares around the previous stack. This ensures a
216-
* router can use `stack()` and then another entity can wrap a router with additional middlewares.
215+
* router can use {@see stackMiddleware()} and then another entity can wrap a router with additional middlewares.
217216
*
218217
* @throws \Error If the server has started.
219218
*/
@@ -227,9 +226,10 @@ public function stackMiddleware(Middleware ...$middlewares): void
227226
}
228227

229228
/**
230-
* Specifies an instance of RequestHandler that is used if no routes match.
229+
* Specifies an instance of {@see RequestHandler} that is used if no routes match.
231230
*
232-
* If no fallback is given, a 404 response is returned from `respond()` when no matching routes are found.
231+
* If no fallback is given, a 404 response is returned from {@see handleRequest()} when no matching routes are
232+
* found.
233233
*
234234
* @throws \Error If the server has started.
235235
*/

0 commit comments

Comments
 (0)