Handler typedef

Handler = FutureOr<Result> Function(Request req)

A function that processes a Request to produce a Result.

For example, a static file handler may extract the requested URI from the Request, read the corresponding file from the filesystem, and return a Response containing the file data as its Body.

A function which produces a Handler, either by wrapping one or more other handlers, or using function composition is known as a "middleware".

A Handler may receive a Request directly from an HTTP server adapter or it may have been processed by other middleware. Similarly, the resulting Result may be directly returned to an HTTP server adapter or have further processing done by other middleware.

Basic Handler

Response myHandler(Request req) {
  return Response.ok(
    body: Body.fromString('Hello, World!'),
  );
}

Async Handler

Future<Response> asyncHandler(Request req) async {
  final data = await fetchDataFromDatabase();
  return Response.ok(
    body: Body.fromString(jsonEncode(data), mimeType: MimeType.json),
  );
}

Handler with Path Parameters

// Route: /users/:id
Handler userHandler(Request req) {
  final id = req.pathParameters[#id];
  return Response.ok(
    body: Body.fromString('User ID: $id'),
  );
}

Implementation

typedef Handler = FutureOr<Result> Function(Request req);