Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(684)

Unified Diff: lib/src/util/one_off_handler.dart

Issue 962363003: Add a shelf handler for running one-off handlers. (Closed) Base URL: git@github.com:dart-lang/unittest@master
Patch Set: Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | test/one_off_handler_test.dart » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: lib/src/util/one_off_handler.dart
diff --git a/lib/src/util/one_off_handler.dart b/lib/src/util/one_off_handler.dart
new file mode 100644
index 0000000000000000000000000000000000000000..bffefe8dc63a9ad224315f27a412ee0a76c3beae
--- /dev/null
+++ b/lib/src/util/one_off_handler.dart
@@ -0,0 +1,47 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library unittest.one_off_handler;
+
+import 'package:path/path.dart' as p;
+import 'package:shelf/shelf.dart' as shelf;
+
+/// A Shelf handler that provides support for one-time handlers.
+///
+/// This is useful for handlers that only expect to be hit once before becoming
+/// invalid and don't need to have a persistent URL.
+class OneOffHandler {
+ /// A map from URL paths to handlers.
+ final _handlers = new Map<String, shelf.Handler>();
+
+ /// The counter of handlers that have been activated.
+ var _counter = 0;
+
+ /// The actual [shelf.Handler] that dispatches requests.
+ shelf.Handler get handler => _onRequest;
+
+ /// Creates a new one-off handler that forwards to [handler].
+ ///
+ /// Returns a string that's the URL path for hitting this handler, relative to
+ /// the URL for the one-off handler itself.
+ ///
+ /// [handler] will be unmounted as soon as it receives a request.
+ String create(shelf.Handler handler) {
+ var path = _counter.toString();
+ _handlers[path] = handler;
+ _counter++;
+ return path;
+ }
+
+ /// Dispatches [request] to the appropriate handler.
+ _onRequest(shelf.Request request) {
+ // Skip the first component because it's always "/".
+ var components = p.url.split(request.url.path).skip(1).toList();
+ if (components.isEmpty) return new shelf.Response.notFound(null);
+
+ var handler = _handlers.remove(components.removeAt(0));
+ if (handler == null) return new shelf.Response.notFound(null);
+ return handler(request);
+ }
+}
« no previous file with comments | « no previous file | test/one_off_handler_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698