compressResponse function
FutureOr<Response>
compressResponse(
- Request request,
- Response response, {
- APIResponseCompression compression = const APIResponseCompression(),
- bool addCompressionRatioHeader = true,
- bool addServerTiming = true,
Compresses response with the best encoding accepted by request
(see APIResponseCompression.resolveRequestEncoding).
HEADrequests are not compressed (no body to compress): only theVaryheader is added, and theContent-Lengthis kept.- Adds
Vary: Accept-Encodingifresponsecan be compressed, even ifrequestdoes not accept any encoding (for caches). - Falls back to the next accepted encoding if one fails.
- A large Brotli encoding runs in a background Isolate (see APIBrotli.encodeAsync).
- The uncompressed length is set in the
Response.context(see uncompressedContentLength). - If
addCompressionRatioHeaderistrueit adds the headerX-Compression-Ratio, with compression info, e.g.:0.55 (550/1000) - If
addServerTimingistrue, includes or appends the encoding timing to theserver-timingheader (entriesbrorgzip).
Implementation
FutureOr<Response> compressResponse(
Request request,
Response response, {
APIResponseCompression compression = const APIResponseCompression(),
bool addCompressionRatioHeader = true,
bool addServerTiming = true,
}) {
if (!compression.isEnabled) return response;
if (!canCompressResponse(response, minLength: compression.minLength)) {
return response;
}
var vary = mergeVaryHeader(
response.headers[HttpHeaders.varyHeader],
'Accept-Encoding',
);
// Same `Vary` as the `GET`, without a body to compress:
if (request.method == 'HEAD') {
return response.change(headers: {HttpHeaders.varyHeader: vary});
}
var accepted = parseAcceptEncoding(
request.headers[HttpHeaders.acceptEncodingHeader],
);
var encoding = compression.resolveAcceptedEncoding(accepted);
if (encoding == null) {
return response.change(headers: {HttpHeaders.varyHeader: vary});
}
return _compressResponseImpl(
response,
accepted,
encoding,
vary,
compression,
addCompressionRatioHeader,
addServerTiming,
);
}