handler property
Handler
get
handler
Main request handler
Implementation
Handler get handler {
return (Request request) async {
final method = request.method;
final path = '/${request.url.path}';
// Try exact match
final key = '$method:$path';
if (_routes.containsKey(key)) {
return _routes[key]!(request);
}
// Try pattern matching for dynamic routes
for (final entry in _routes.entries) {
final routeKey = entry.key;
if (!routeKey.startsWith('$method:')) continue;
final routePath = routeKey.substring(method.length + 1);
final params = _matchRoute(routePath, path);
if (params != null) {
// Add params to request context
final newRequest = request.change(context: {
...request.context,
'params': params,
});
return entry.value(newRequest);
}
}
// Try serving static files if staticDir is set
if (staticDir != null) {
final staticHandler = createStaticHandler(
staticDir!,
defaultDocument: 'index.html',
);
final staticResponse = await staticHandler(request);
if (staticResponse.statusCode != 404) {
return staticResponse;
}
// For SPA routing, try serving index.html for HTML requests
if (request.headers['accept']?.contains('text/html') ?? false) {
final indexFile = File('$staticDir/index.html');
if (indexFile.existsSync()) {
return Response.ok(
indexFile.readAsStringSync(),
headers: {'Content-Type': 'text/html'},
);
}
}
}
return Response.notFound(
jsonEncode({'error': 'Not found'}),
headers: {'Content-Type': 'application/json'},
);
};
}