compressResponse function

FutureOr<Response> compressResponse(
  1. Request request,
  2. Response response, {
  3. APIResponseCompression compression = const APIResponseCompression(),
  4. bool addCompressionRatioHeader = true,
  5. bool addServerTiming = true,
})

Compresses response with the best encoding accepted by request (see APIResponseCompression.resolveRequestEncoding).

  • HEAD requests are not compressed (no body to compress): only the Vary header is added, and the Content-Length is kept.
  • Adds Vary: Accept-Encoding if response can be compressed, even if request does 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 addCompressionRatioHeader is true it adds the header X-Compression-Ratio, with compression info, e.g.: 0.55 (550/1000)
  • If addServerTiming is true, includes or appends the encoding timing to the server-timing header (entries br or gzip).

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,
  );
}