OLD | NEW |
(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 shelf.body; |
| 6 |
| 7 import 'dart:async'; |
| 8 import 'dart:convert'; |
| 9 |
| 10 /// The body of a request or response. |
| 11 /// |
| 12 /// This tracks whether the body has been read. It's separate from [Message] |
| 13 /// because the message may be changed with [Message.change], but each instance |
| 14 /// should share a notion of whether the body was read. |
| 15 class Body { |
| 16 /// The contents of the message body. |
| 17 /// |
| 18 /// This will be `null` after [read] is called. |
| 19 Stream<List<int>> _stream; |
| 20 |
| 21 Body._(this._stream); |
| 22 |
| 23 /// Converts [body] to a byte stream and wraps it in a [Body]. |
| 24 /// |
| 25 /// [body] may be either a [Body], a [String], a [Stream<List<int>>], or |
| 26 /// `null`. If it's a [String], [encoding] will be used to convert it to a |
| 27 /// [Stream<List<int>>]. |
| 28 factory Body(body, [Encoding encoding]) { |
| 29 if (encoding == null) encoding = UTF8; |
| 30 |
| 31 if (body is Body) return body; |
| 32 |
| 33 var stream; |
| 34 if (body == null) { |
| 35 stream = new Stream.fromIterable([]); |
| 36 } else if (body is String) { |
| 37 stream = new Stream.fromIterable([encoding.encode(body)]); |
| 38 } else if (body is Stream) { |
| 39 stream = body; |
| 40 } else { |
| 41 throw new ArgumentError('Response body "$body" must be a String or a ' |
| 42 'Stream.'); |
| 43 } |
| 44 |
| 45 return new Body._(stream); |
| 46 } |
| 47 |
| 48 /// Returns a [Stream] representing the body. |
| 49 /// |
| 50 /// Can only be called once. |
| 51 Stream<List<int>> read() { |
| 52 if (_stream == null) { |
| 53 throw new StateError("The 'read' method can only be called once on a " |
| 54 "shelf.Request/shelf.Response object."); |
| 55 } |
| 56 var stream = _stream; |
| 57 _stream = null; |
| 58 return stream; |
| 59 } |
| 60 } |
OLD | NEW |