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

Side by Side 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, 9 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 unified diff | Download patch
« no previous file with comments | « no previous file | test/one_off_handler_test.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 library unittest.one_off_handler;
6
7 import 'package:path/path.dart' as p;
8 import 'package:shelf/shelf.dart' as shelf;
9
10 /// A Shelf handler that provides support for one-time handlers.
11 ///
12 /// This is useful for handlers that only expect to be hit once before becoming
13 /// invalid and don't need to have a persistent URL.
14 class OneOffHandler {
15 /// A map from URL paths to handlers.
16 final _handlers = new Map<String, shelf.Handler>();
17
18 /// The counter of handlers that have been activated.
19 var _counter = 0;
20
21 /// The actual [shelf.Handler] that dispatches requests.
22 shelf.Handler get handler => _onRequest;
23
24 /// Creates a new one-off handler that forwards to [handler].
25 ///
26 /// Returns a string that's the URL path for hitting this handler, relative to
27 /// the URL for the one-off handler itself.
28 ///
29 /// [handler] will be unmounted as soon as it receives a request.
30 String create(shelf.Handler handler) {
31 var path = _counter.toString();
32 _handlers[path] = handler;
33 _counter++;
34 return path;
35 }
36
37 /// Dispatches [request] to the appropriate handler.
38 _onRequest(shelf.Request request) {
39 // Skip the first component because it's always "/".
40 var components = p.url.split(request.url.path).skip(1).toList();
41 if (components.isEmpty) return new shelf.Response.notFound(null);
42
43 var handler = _handlers.remove(components.removeAt(0));
44 if (handler == null) return new shelf.Response.notFound(null);
45 return handler(request);
46 }
47 }
OLDNEW
« 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