canGzipEncodeResponse function

bool canGzipEncodeResponse(
  1. Response response, {
  2. int minimalGzipContentLength = _defaultMinimalGzipContentLength,
  3. _AlreadyCompressedContentType? alreadyCompressedContentType,
})

Returns true if response can be compressed.

  • minimalGzipContentLength is the minimal size for a content to be compressed. Default to 512.
  • alreadyCompressedContentType is a function that returns true if the passed contentType is already compressed, like a PNG, JPEG or Zip.

Checks:

  • Content-Encoding: if already present, can't change it to gzip.
  • Content-Type: checks if isAlreadyCompressedContentType.
  • Content-Length: checks if too small for compression (< 512).

Implementation

bool canGzipEncodeResponse(Response response,
    {int minimalGzipContentLength = _defaultMinimalGzipContentLength,
    _AlreadyCompressedContentType? alreadyCompressedContentType}) {
  var headerContentEncoding =
      response.headers[HttpHeaders.contentEncodingHeader];

  // If the response already defines a `Content-Encoding` header it
  // won't apply the the `gzip` encoding to preserve the response behavior.
  if (headerContentEncoding != null && headerContentEncoding.isNotEmpty) {
    return false;
  }

  var responseContentLength = response.contentLength;

  // A small body will not benefit from being compressed:
  if (responseContentLength != null &&
      responseContentLength < minimalGzipContentLength) {
    return false;
  }

  var headerContentType = response.headers[HttpHeaders.contentTypeHeader];

  // Do not compress if the `Content-Type` is an already compressed type:
  if (headerContentType != null) {
    alreadyCompressedContentType ??= isAlreadyCompressedContentType;
    if (alreadyCompressedContentType(headerContentType)) {
      return false;
    }
  }

  return true;
}