canGzipEncodeResponse function
bool
canGzipEncodeResponse(
- Response response, {
- int minimalGzipContentLength = _defaultMinimalGzipContentLength,
- _AlreadyCompressedContentType? alreadyCompressedContentType,
Returns true
if response
can be compressed.
minimalGzipContentLength
is the minimal size for a content to be compressed. Default to512
.alreadyCompressedContentType
is a function that returnstrue
if the passedcontentType
is already compressed, like aPNG
,JPEG
orZip
.
Checks:
Content-Encoding
: if already present, can't change it togzip
.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;
}