rateLimit function
Rate limiting middleware
Limits each IP to maxRequests per window. Uses in-memory storage.
Implementation
Middleware rateLimit({
int maxRequests = 100,
Duration window = const Duration(minutes: 1),
}) {
final _requests = <String, List<DateTime>>{};
return (Handler innerHandler) {
return (Request request) async {
final ip = (request.context['shelf.io.connection_info'] as HttpConnectionInfo?)
?.remoteAddress.address ?? 'unknown';
final now = DateTime.now();
final cutoff = now.subtract(window);
// Clean old entries and add current
final timestamps = (_requests[ip] ?? [])
.where((t) => t.isAfter(cutoff))
.toList()
..add(now);
_requests[ip] = timestamps;
if (timestamps.length > maxRequests) {
return Response(
429,
body: jsonEncode({'error': 'Too many requests'}),
headers: {
'Content-Type': 'application/json',
'Retry-After': window.inSeconds.toString(),
},
);
}
return innerHandler(request);
};
};
}