simple_http_router 2.0.1-beta copy "simple_http_router: ^2.0.1-beta" to clipboard
simple_http_router: ^2.0.1-beta copied to clipboard

discontinued

A very simple http router / multiplexer to handle HttpRequests and middleware

Quick Example #

void main(List<String> args) async {
  final server = await HttpServer.bind('localhost', 8080);
  final router = Router();

  router.register(Route('/index', HttpMethodHandler(get: indexHandler)));

  final indexMiddlewareHandler =
      MiddlewareHandler(indexHandler, before: const [setCookieMiddleware]);
  router.register(
      Route('/cookie', HttpMethodHandler(get: indexMiddlewareHandler)));

  await for (final request in server) {
    router.handle(request);
  }
}

Documentation #

Router registers multiple Routes and forwards a HttpRequest to the right one (and only one!). If you enable assertions you will get warned when a path is overshadowed by another one. Always register Routes from specific to less specific. When no path matches the request, the (provided) 'not found' handler will be called.

Route is just a container type that takes a path in glob notation, for example '/public/*', and a HttpMethodHandler, that takes Handlers for the various HTTP-Methods the route could be called with. When the route is called with a method for which no Handler is registered, the (provided) bad request handler will be called.

To execute middleware before or after the route's handler, instead of providing a Handler function, just register a MiddlewareHandler, that takes varius middleware as List. To prevent any further middleware from executing (for example because of failed authorization), you must call the canzel() method of the provided Context object.

Differentiate between middleware and handlers #

The signature for middleware is exactly the same as for handlers; their difference is purely semantical. Middleware is meant to perform reoccuring, route independent tasks like fetching a user id or check the session token; but it does not handle the requested action like serving a page or putting updated user information into the database; that is the handler's duty. Middleware can, though, "short circuit" a request, for example when the session has expired; in that case there wouldn't be any need to call the handler. Just remember to call Context.cancel() in such a case.

0
likes
40
pub points
0%
popularity

Publisher

unverified uploader

A very simple http router / multiplexer to handle HttpRequests and middleware

Repository (GitLab)
View/report issues

License

MIT (LICENSE)

Dependencies

quiver

More

Packages that depend on simple_http_router