Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add BaseResponseWithUrl.url #1109

Merged
merged 10 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pkgs/http/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 1.2.0-wip
## 1.2.0

* Add `MockClient.pngResponse`, which makes it easier to fake image responses.
* Added the ability to fetch the URL of the response through `BaseResponseWithUrl`.
* Add the ability to get headers as a `Map<String, List<String>` to
`BaseResponse`.

Expand Down
5 changes: 3 additions & 2 deletions pkgs/http/lib/http.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import 'src/streamed_request.dart';

export 'src/base_client.dart';
export 'src/base_request.dart';
export 'src/base_response.dart' show BaseResponse, HeadersWithSplitValues;
export 'src/base_response.dart'
show BaseResponse, BaseResponseWithUrl, HeadersWithSplitValues;
export 'src/byte_stream.dart';
export 'src/client.dart' hide zoneClient;
export 'src/exception.dart';
Expand All @@ -25,7 +26,7 @@ export 'src/multipart_request.dart';
export 'src/request.dart';
export 'src/response.dart';
export 'src/streamed_request.dart';
export 'src/streamed_response.dart';
export 'src/streamed_response.dart' show StreamedResponse;

/// Sends an HTTP HEAD request with the given headers to the given URL.
///
Expand Down
26 changes: 19 additions & 7 deletions pkgs/http/lib/src/base_request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,25 @@ abstract class BaseRequest {
try {
var response = await client.send(this);
var stream = onDone(response.stream, client.close);
return StreamedResponse(ByteStream(stream), response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase);

if (response case BaseResponseWithUrl(:final url)) {
return StreamedResponseV2(ByteStream(stream), response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
url: url,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase);
} else {
return StreamedResponse(ByteStream(stream), response.statusCode,
contentLength: response.contentLength,
request: response.request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase);
}
} catch (_) {
client.close();
rethrow;
Expand Down
34 changes: 34 additions & 0 deletions pkgs/http/lib/src/base_response.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

import 'base_client.dart';
import 'base_request.dart';
import 'client.dart';
import 'response.dart';
import 'streamed_response.dart';

/// The base class for HTTP responses.
///
Expand Down Expand Up @@ -71,6 +74,37 @@ abstract class BaseResponse {
}
}

/// A [BaseResponse] with a [url] field.
///
/// [Client] methods that return a [BaseResponse] subclass, such as [Response]
/// or [StreamedResponse], **may** return a [BaseResponseWithUrl].
///
/// For example:
///
/// ```dart
/// final client = Client();
/// final response = client.get(Uri.https('example.com', '/'));
/// Uri? finalUri;
/// if (response case BaseResponseWithUrl(:final url)) {
/// finalUri = url;
/// }
/// // Do something with `finalUri`.
/// client.close();
/// ```
///
/// [url] will be added to [BaseResponse] when `package:http` version 2 is
/// released and this mixin will be deprecated.
abstract interface class BaseResponseWithUrl implements BaseResponse {
/// The [Uri] of the response returned by the server.
///
/// If no redirects were followed, [url] will be the same as the requested
/// [Uri].
///
/// If redirects were followed, [url] will be the [Uri] of the last redirect
/// that was followed.
abstract final Uri url;
}

/// "token" as defined in RFC 2616, 2.2
/// See https://datatracker.ietf.org/doc/html/rfc2616#section-2.2
const _tokenChars = r"!#$%&'*+\-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`"
Expand Down
5 changes: 4 additions & 1 deletion pkgs/http/lib/src/browser_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,13 @@ class BrowserClient extends BaseClient {
return;
}
var body = (xhr.response as JSArrayBuffer).toDart.asUint8List();
completer.complete(StreamedResponse(
var responseUrl = xhr.responseURL;
var url = responseUrl.isNotEmpty ? Uri.parse(responseUrl) : request.url;
completer.complete(StreamedResponseV2(
ByteStream.fromBytes(body), xhr.status,
contentLength: body.length,
request: request,
url: url,
headers: xhr.responseHeaders,
reasonPhrase: xhr.statusText));
}));
Expand Down
22 changes: 21 additions & 1 deletion pkgs/http/lib/src/io_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'dart:io';

import 'base_client.dart';
import 'base_request.dart';
import 'base_response.dart';
import 'client.dart';
import 'exception.dart';
import 'io_streamed_response.dart';
Expand Down Expand Up @@ -46,6 +47,22 @@ class _ClientSocketException extends ClientException
String toString() => 'ClientException with $cause, uri=$uri';
}

class _IOStreamedResponseV2 extends IOStreamedResponse
implements BaseResponseWithUrl {
@override
final Uri url;

_IOStreamedResponseV2(super.stream, super.statusCode,
{required this.url,
super.contentLength,
super.request,
super.headers,
super.isRedirect,
super.persistentConnection,
super.reasonPhrase,
super.inner});
brianquinlan marked this conversation as resolved.
Show resolved Hide resolved
}

/// A `dart:io`-based HTTP [Client].
///
/// If there is a socket-level failure when communicating with the server
Expand Down Expand Up @@ -116,7 +133,7 @@ class IOClient extends BaseClient {
headers[key] = values.map((value) => value.trimRight()).join(',');
});

return IOStreamedResponse(
return _IOStreamedResponseV2(
response.handleError((Object error) {
final httpException = error as HttpException;
throw ClientException(httpException.message, httpException.uri);
Expand All @@ -127,6 +144,9 @@ class IOClient extends BaseClient {
request: request,
headers: headers,
isRedirect: response.isRedirect,
url: response.redirects.isNotEmpty
? response.redirects.last.location
: request.url,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase,
inner: response);
Expand Down
17 changes: 17 additions & 0 deletions pkgs/http/lib/src/streamed_response.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,20 @@ class StreamedResponse extends BaseResponse {
super.reasonPhrase})
: stream = toByteStream(stream);
}

/// This class is private to `package:http` and will be removed when
/// `package:http` v2 is released.
class StreamedResponseV2 extends StreamedResponse
implements BaseResponseWithUrl {
@override
final Uri url;

StreamedResponseV2(super.stream, super.statusCode,
{required this.url,
super.contentLength,
super.request,
super.headers,
super.isRedirect,
super.persistentConnection,
super.reasonPhrase});
}
2 changes: 1 addition & 1 deletion pkgs/http/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: http
version: 1.2.0-wip
version: 1.2.0
description: A composable, multi-platform, Future-based API for HTTP requests.
repository: https://github.com/dart-lang/http/tree/master/pkgs/http

Expand Down
9 changes: 8 additions & 1 deletion pkgs/http/test/io/request_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,22 @@ void main() {
final response = await request.send();

expect(response.statusCode, equals(302));
expect(
response,
isA<http.BaseResponseWithUrl>()
.having((r) => r.url, 'url', serverUrl.resolve('/redirect')));
});

test('with redirects', () async {
final request = http.Request('GET', serverUrl.resolve('/redirect'));
final response = await request.send();

expect(response.statusCode, equals(200));
final bytesString = await response.stream.bytesToString();
expect(bytesString, parse(containsPair('path', '/')));
expect(
response,
isA<http.BaseResponseWithUrl>()
.having((r) => r.url, 'url', serverUrl.resolve('/')));
});

test('exceeding max redirects', () async {
Expand Down