platform/example/rate_limit.dart

35 lines
1.1 KiB
Dart
Raw Normal View History

2019-08-14 18:49:14 +00:00
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_framework/http.dart';
import 'package:angel_security/angel_security.dart';
2019-08-14 20:13:37 +00:00
import 'package:logging/logging.dart';
import 'package:pretty_logging/pretty_logging.dart';
2019-08-14 18:49:14 +00:00
main() async {
2019-08-14 20:13:37 +00:00
// Logging boilerplate.
Logger.root.onRecord.listen(prettyLog);
2019-08-14 20:06:40 +00:00
// Create an app, and HTTP driver.
2019-08-14 20:13:37 +00:00
var app = Angel(logger: Logger('rate_limit')), http = AngelHttp(app);
2019-08-14 20:06:40 +00:00
// Create a simple in-memory rate limiter that limits users to 5
// queries per hour.
//
// In this case, we rate limit users by IP address.
var rateLimiter =
InMemoryRateLimiter(5, Duration(hours: 1), (req, res) => req.ip);
// `RateLimiter.handleRequest` is a middleware, and can be used anywhere
// a middleware can be used. In this case, we apply the rate limiter to
// *all* incoming requests.
app.fallback(rateLimiter.handleRequest);
// Basic routes.
app
..get('/', (req, res) => 'Hello!')
..fallback((req, res) => throw AngelHttpException.notFound());
// Start the server.
await http.startServer('127.0.0.1', 3000);
print('Rate limiting example listening at ${http.uri}');
2019-08-14 18:49:14 +00:00
}