toMiddleware method

  1. @override
Middleware toMiddleware()
override

Builds the shelf middleware this value configures.

Implementation

@override
Middleware toMiddleware() {
  return (Handler inner) {
    return (Request request) async {
      final accepts = _acceptsGzip(
        RequestParts.of(request).headers['accept-encoding'],
      );

      final response = await inner(request);
      // `Vary` goes on either way, so a cache never reuses one client's
      // encoding for another's request.
      final varied = response.change(
        headers: {'vary': _vary(response.headers['vary'])},
      );

      if (!accepts || !_worthCompressing(varied)) return varied;

      return varied.change(
        headers: {
          'content-encoding': 'gzip',
          // The encoded length is not the declared one, and computing it
          // would mean buffering the whole body.
          'content-length': null,
        },
        body: GZipCodec(level: level)
            .encoder
            .bind(varied.read().map(List<int>.from)),
      );
    };
  };
}