shelf_route 0.1.0+2 shelf_route: ^0.1.0+2 copied to clipboard
Routing middleware for Shelf
Router for Dart Shelf #
Introduction #
Provides Shelf middleware for defining routes.
Shelf Route makes it easy to define routes in a modular way. How?
- A
Router
is simply a Shelf Middleware component. - You can define a single Router for your whole application or as many as you like in a heirarchical structure.
- When a Router passes a request to a child route it first modifies the request as follows:
- The route's
path
is removed from the start ofpathInfo
. e.g./banking/accounts
->/accounts
- The route's
path
is appended to thescriptName
. e.g./
->/banking
- That supports modularity in the child routes as the pathInfo only contains the path relative to that component.
- The route's
Example #
See example/routing_example.dart
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_route/shelf_route.dart' as route;
void main() {
var publicRoute = const shelf.Stack()
.addHandler(_echoRequest);
var router = (route.router()
..addRoute(publicRoute, path: '/public')
..addRoute(_bankingRoutes(), path: '/banking'))
.handler;
var handler = const shelf.Stack()
.addMiddleware(shelf.logRequests())
.addHandler(router);
io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at http://${server.address.host}:${server.port}');
});
}
shelf.Response _echoRequest(shelf.Request request) {
return new shelf.Response.ok('Request for "${request.pathInfo}"');
}
// supports modularity with routes. i.e. here the banking section has it's own routes
// these are relative to where the main router places them
shelf.Handler _bankingRoutes() {
var accountsRoute = const shelf.Stack()
.addHandler(_echoRequest);
var transfersRoute = const shelf.Stack()
.addHandler(_echoRequest);
var bankingRouter = (route.router()
..addRoute(accountsRoute, path: '/accounts')
..addRoute(transfersRoute, path: '/transfers'))
.handler;
var bankingRoute = const shelf.Stack()
// .addMiddleware(authenticator); // obviously they would be authenticated
.addHandler(bankingRouter);
return bankingRoute;
}
TODO #
- Improve tests
- Add support for path variables and access to their values in downstream handlers