platform/packages/cache/example/main.dart

37 lines
1.1 KiB
Dart
Raw Normal View History

import 'package:angel3_cache/angel3_cache.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
2018-04-02 02:43:00 +00:00
import 'package:glob/glob.dart';
main() async {
2021-02-14 05:22:25 +00:00
var app = Angel();
2018-04-02 02:43:00 +00:00
// Cache a glob
2021-02-14 05:22:25 +00:00
var cache = ResponseCache()
2018-04-02 02:43:00 +00:00
..patterns.addAll([
2021-02-14 05:22:25 +00:00
Glob('/*.txt'),
2018-04-02 02:43:00 +00:00
]);
// Handle `if-modified-since` header, and also send cached content
2018-10-21 09:35:04 +00:00
app.fallback(cache.handleRequest);
2018-04-02 02:43:00 +00:00
// A simple handler that returns a different result every time.
2021-02-14 05:22:25 +00:00
app.get(
'/date.txt', (req, res) => res.write(DateTime.now().toIso8601String()));
2018-04-02 02:43:00 +00:00
// Support purging the cache.
2018-10-21 09:35:04 +00:00
app.addRoute('PURGE', '*', (req, res) {
2021-02-14 05:22:25 +00:00
if (req.ip != '127.0.0.1') throw AngelHttpException.forbidden();
2018-04-02 02:43:00 +00:00
cache.purge(req.uri!.path);
print('Purged ${req.uri!.path}');
2018-04-02 02:43:00 +00:00
});
// The response finalizer that actually saves the content
app.responseFinalizers.add(cache.responseFinalizer);
2021-02-14 05:22:25 +00:00
var http = AngelHttp(app);
2018-04-02 02:43:00 +00:00
var server = await http.startServer('127.0.0.1', 3000);
print('Listening at http://${server.address.address}:${server.port}');
}