NewCompressor creates a new Compressor that will handle encoding responses. The level should be one of the ones defined in the flate package. The types are the content types that are allowed to be compressed.
(logger slog.Logger, level int, cacheDir string, orig http.FileSystem)
| 68 | // The level should be one of the ones defined in the flate package. |
| 69 | // The types are the content types that are allowed to be compressed. |
| 70 | func NewCompressor(logger slog.Logger, level int, cacheDir string, orig http.FileSystem) *Compressor { |
| 71 | c := &Compressor{ |
| 72 | logger: logger.Named("cachecompress"), |
| 73 | level: level, |
| 74 | encoders: make(map[string]EncoderFunc), |
| 75 | pooledEncoders: make(map[string]*sync.Pool), |
| 76 | cacheDir: cacheDir, |
| 77 | orig: orig, |
| 78 | cache: make(map[cacheKey]ref), |
| 79 | } |
| 80 | |
| 81 | // Set the default encoders. The precedence order uses the reverse |
| 82 | // ordering that the encoders were added. This means adding new encoders |
| 83 | // will move them to the front of the order. |
| 84 | // |
| 85 | // TODO: |
| 86 | // lzma: Opera. |
| 87 | // sdch: Chrome, Android. Gzip output + dictionary header. |
| 88 | // br: Brotli, see https://github.com/go-chi/chi/pull/326 |
| 89 | |
| 90 | // HTTP 1.1 "deflate" (RFC 2616) stands for DEFLATE data (RFC 1951) |
| 91 | // wrapped with zlib (RFC 1950). The zlib wrapper uses Adler-32 |
| 92 | // checksum compared to CRC-32 used in "gzip" and thus is faster. |
| 93 | // |
| 94 | // But.. some old browsers (MSIE, Safari 5.1) incorrectly expect |
| 95 | // raw DEFLATE data only, without the mentioned zlib wrapper. |
| 96 | // Because of this major confusion, most modern browsers try it |
| 97 | // both ways, first looking for zlib headers. |
| 98 | // Quote by Mark Adler: http://stackoverflow.com/a/9186091/385548 |
| 99 | // |
| 100 | // The list of browsers having problems is quite big, see: |
| 101 | // http://zoompf.com/blog/2012/02/lose-the-wait-http-compression |
| 102 | // https://web.archive.org/web/20120321182910/http://www.vervestudios.co/projects/compression-tests/results |
| 103 | // |
| 104 | // That's why we prefer gzip over deflate. It's just more reliable |
| 105 | // and not significantly slower than deflate. |
| 106 | c.SetEncoder("deflate", encoderDeflate) |
| 107 | |
| 108 | // TODO: Exception for old MSIE browsers that can't handle non-HTML? |
| 109 | // https://zoompf.com/blog/2012/02/lose-the-wait-http-compression |
| 110 | c.SetEncoder("gzip", encoderGzip) |
| 111 | |
| 112 | // NOTE: Not implemented, intentionally: |
| 113 | // case "compress": // LZW. Deprecated. |
| 114 | // case "bzip2": // Too slow on-the-fly. |
| 115 | // case "zopfli": // Too slow on-the-fly. |
| 116 | // case "xz": // Too slow on-the-fly. |
| 117 | return c |
| 118 | } |
| 119 | |
| 120 | // SetEncoder can be used to set the implementation of a compression algorithm. |
| 121 | // |