| 1 |
// Package gzhttp provides HTTP middleware for compressing response bodies |
| 2 |
// using gzip or zstd (RFC 8878). It wraps http.Handler to transparently |
| 3 |
// compress responses based on the client's Accept-Encoding header. |
| 4 |
// |
| 5 |
// The package supports content negotiation, preferring zstd when both |
| 6 |
// encodings are accepted with equal quality values. Both encodings are |
| 7 |
// enabled by default with conservative settings for broad compatibility. |
| 8 |
// |
| 9 |
// Basic usage: |
| 10 |
// |
| 11 |
// wrapper, _ := gzhttp.NewWrapper() |
| 12 |
// http.Handle("/", wrapper(myHandler)) |
| 13 |
// |
| 14 |
// Or use the convenience function: |
| 15 |
// |
| 16 |
// http.Handle("/", gzhttp.GzipHandler(myHandler)) |
| 17 |
// |
| 18 |
// Custom compression implementations can be provided via GzipImplementation |
| 19 |
// and ZstdImplementation options. |
| 20 |
// |
| 21 |
// For HTTP clients, the Transport function wraps an http.RoundTripper to |
| 22 |
// automatically request and decompress gzip/zstd responses: |
| 23 |
// |
| 24 |
// client := http.Client{ |
| 25 |
// Transport: gzhttp.Transport(http.DefaultTransport), |
| 26 |
// } |
| 27 |
package gzhttp |
| 28 |
|
| 29 |
import ( |
| 30 |
"bufio" |
| 31 |
"crypto/rand" |
| 32 |
"crypto/sha256" |
| 33 |
"encoding/binary" |
| 34 |
"errors" |
| 35 |
"fmt" |
| 36 |
"hash/crc32" |
| 37 |
"io" |
| 38 |
"math" |
| 39 |
"math/bits" |
| 40 |
"mime" |
| 41 |
"net" |
| 42 |
"net/http" |
| 43 |
"strconv" |
| 44 |
"strings" |
| 45 |
"sync" |
| 46 |
|
| 47 |
"github.com/klauspost/compress/gzhttp/writer" |
| 48 |
"github.com/klauspost/compress/gzhttp/writer/gzkp" |
| 49 |
"github.com/klauspost/compress/gzhttp/writer/zstdkp" |
| 50 |
"github.com/klauspost/compress/gzip" |
| 51 |
"github.com/klauspost/compress/zstd" |
| 52 |
) |
| 53 |
|
| 54 |
const ( |
| 55 |
// HeaderNoCompression can be used to disable compression. |
| 56 |
// Any header value will disable compression. |
| 57 |
// The Header is always removed from output. |
| 58 |
HeaderNoCompression = "No-Gzip-Compression" |
| 59 |
|
| 60 |
vary = "Vary" |
| 61 |
acceptEncoding = "Accept-Encoding" |
| 62 |
contentEncoding = "Content-Encoding" |
| 63 |
contentRange = "Content-Range" |
| 64 |
acceptRanges = "Accept-Ranges" |
| 65 |
contentType = "Content-Type" |
| 66 |
contentLength = "Content-Length" |
| 67 |
eTag = "Etag" |
| 68 |
) |
| 69 |
|
| 70 |
type codings map[string]float64 |
| 71 |
|
| 72 |
const ( |
| 73 |
// DefaultQValue is the default qvalue to assign to an encoding if no explicit qvalue is set. |
| 74 |
// This is actually kind of ambiguous in RFC 2616, so hopefully it's correct. |
| 75 |
// The examples seem to indicate that it is. |
| 76 |
DefaultQValue = 1.0 |
| 77 |
|
| 78 |
// DefaultMinSize is the default minimum size until we enable gzip compression. |
| 79 |
// 1500 bytes is the MTU size for the internet since that is the largest size allowed at the network layer. |
| 80 |
// If you take a file that is 1300 bytes and compress it to 800 bytes, it’s still transmitted in that same 1500 byte packet regardless, so you’ve gained nothing. |
| 81 |
// That being the case, you should restrict the gzip compression to files with a size (plus header) greater than a single packet, |
| 82 |
// 1024 bytes (1KB) is therefore default. |
| 83 |
DefaultMinSize = 1024 |
| 84 |
) |
| 85 |
|
| 86 |
// encoding represents the compression encoding to use. |
| 87 |
type encoding int |
| 88 |
|
| 89 |
const ( |
| 90 |
encodingNone encoding = iota |
| 91 |
encodingGzip |
| 92 |
encodingZstd |
| 93 |
) |
| 94 |
|
| 95 |
// GzipResponseWriter provides an http.ResponseWriter interface, which gzips |
| 96 |
// bytes before writing them to the underlying response. This doesn't close the |
| 97 |
// writers, so don't forget to do that. |
| 98 |
// It can be configured to skip response smaller than minSize. |
| 99 |
type GzipResponseWriter struct { |
| 100 |
http.ResponseWriter |
| 101 |
level int |
| 102 |
gwFactory writer.GzipWriterFactory |
| 103 |
gw writer.GzipWriter |
| 104 |
|
| 105 |
// Zstd support |
| 106 |
enc encoding |
| 107 |
zstdLevel int |
| 108 |
zstdFactory writer.ZstdWriterFactory |
| 109 |
zw writer.ZstdWriter |
| 110 |
zstdJitter []byte // Jitter to write as skippable frame on Close |
| 111 |
|
| 112 |
code int // Saves the WriteHeader value. |
| 113 |
|
| 114 |
minSize int // Specifies the minimum response size to gzip. If the response length is bigger than this value, it is compressed. |
| 115 |
buf []byte // Holds the first part of the write before reaching the minSize or the end of the write. |
| 116 |
ignore bool // If true, then we immediately passthru writes to the underlying ResponseWriter. |
| 117 |
keepAcceptRanges bool // Keep "Accept-Ranges" header. |
| 118 |
setContentType bool // Add content type, if missing and detected. |
| 119 |
suffixETag string // Suffix to add to ETag header if response is compressed. |
| 120 |
dropETag bool // Drop ETag header if response is compressed (supersedes suffixETag). |
| 121 |
sha256Jitter bool // Use sha256 for jitter. |
| 122 |
randomJitter string // Add random bytes to output as header field. |
| 123 |
jitterBuffer int // Maximum buffer to accumulate before doing jitter. |
| 124 |
|
| 125 |
contentTypeFilter func(ct string) bool // Only compress if the response is one of these content-types. All are accepted if empty. |
| 126 |
} |
| 127 |
|
| 128 |
type GzipResponseWriterWithCloseNotify struct { |
| 129 |
*GzipResponseWriter |
| 130 |
} |
| 131 |
|
| 132 |
func (w GzipResponseWriterWithCloseNotify) CloseNotify() <-chan bool { |
| 133 |
return w.ResponseWriter.(http.CloseNotifier).CloseNotify() |
| 134 |
} |
| 135 |
|
| 136 |
// Write appends data to the gzip writer. |
| 137 |
func (w *GzipResponseWriter) Write(b []byte) (int, error) { |
| 138 |
// Compression writer is initialized. Use it. |
| 139 |
if w.gw != nil { |
| 140 |
return w.gw.Write(b) |
| 141 |
} |
| 142 |
if w.zw != nil { |
| 143 |
return w.zw.Write(b) |
| 144 |
} |
| 145 |
|
| 146 |
// If we have already decided not to compress, immediately passthrough. |
| 147 |
if w.ignore { |
| 148 |
return w.ResponseWriter.Write(b) |
| 149 |
} |
| 150 |
|
| 151 |
// Save the write into a buffer for later use in compression responseWriter |
| 152 |
// (if content is long enough) or at close with regular responseWriter. |
| 153 |
wantBuf := max(w.minSize, 512) |
| 154 |
if w.jitterBuffer > 0 && w.jitterBuffer > wantBuf { |
| 155 |
wantBuf = w.jitterBuffer |
| 156 |
} |
| 157 |
toAdd := len(b) |
| 158 |
if len(w.buf)+toAdd > wantBuf { |
| 159 |
toAdd = wantBuf - len(w.buf) |
| 160 |
} |
| 161 |
w.buf = append(w.buf, b[:toAdd]...) |
| 162 |
remain := b[toAdd:] |
| 163 |
hdr := w.Header() |
| 164 |
|
| 165 |
// Only continue if they didn't already choose an encoding or a known unhandled content length or type. |
| 166 |
if len(hdr[HeaderNoCompression]) == 0 && hdr.Get(contentEncoding) == "" && hdr.Get(contentRange) == "" { |
| 167 |
// Check more expensive parts now. |
| 168 |
cl, _ := atoi(hdr.Get(contentLength)) |
| 169 |
ct := hdr.Get(contentType) |
| 170 |
if cl == 0 || cl >= w.minSize && (ct == "" || w.contentTypeFilter(ct)) { |
| 171 |
// If the current buffer is less than minSize and a Content-Length isn't set, then wait until we have more data. |
| 172 |
if len(w.buf) < w.minSize && cl == 0 || (w.jitterBuffer > 0 && len(w.buf) < w.jitterBuffer) { |
| 173 |
return len(b), nil |
| 174 |
} |
| 175 |
|
| 176 |
// If the Content-Length is larger than minSize or the current buffer is larger than minSize, then continue. |
| 177 |
if cl >= w.minSize || len(w.buf) >= w.minSize { |
| 178 |
// If a Content-Type wasn't specified, infer it from the current buffer when the response has a body. |
| 179 |
if ct == "" && bodyAllowedForStatus(w.code) && len(w.buf) > 0 { |
| 180 |
ct = http.DetectContentType(w.buf) |
| 181 |
|
| 182 |
// Handles the intended case of setting a nil Content-Type (as for http/server or http/fs) |
| 183 |
// Set the header only if the key does not exist |
| 184 |
if _, ok := hdr[contentType]; w.setContentType && !ok { |
| 185 |
hdr.Set(contentType, ct) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
// If the Content-Type is acceptable, initialize the compression writer. |
| 190 |
if w.contentTypeFilter(ct) { |
| 191 |
if err := w.startCompression(remain); err != nil { |
| 192 |
return 0, err |
| 193 |
} |
| 194 |
if len(remain) > 0 { |
| 195 |
if w.gw != nil { |
| 196 |
if _, err := w.gw.Write(remain); err != nil { |
| 197 |
return 0, err |
| 198 |
} |
| 199 |
} else if w.zw != nil { |
| 200 |
if _, err := w.zw.Write(remain); err != nil { |
| 201 |
return 0, err |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
return len(b), nil |
| 206 |
} |
| 207 |
} |
| 208 |
} |
| 209 |
} |
| 210 |
// If we got here, we should not GZIP this response. |
| 211 |
if err := w.startPlain(); err != nil { |
| 212 |
return 0, err |
| 213 |
} |
| 214 |
if len(remain) > 0 { |
| 215 |
if _, err := w.ResponseWriter.Write(remain); err != nil { |
| 216 |
return 0, err |
| 217 |
} |
| 218 |
} |
| 219 |
return len(b), nil |
| 220 |
} |
| 221 |
|
| 222 |
func (w *GzipResponseWriter) Unwrap() http.ResponseWriter { |
| 223 |
return w.ResponseWriter |
| 224 |
} |
| 225 |
|
| 226 |
var castagnoliTable = crc32.MakeTable(crc32.Castagnoli) |
| 227 |
|
| 228 |
// startCompression initializes the compression writer and writes the buffer. |
| 229 |
func (w *GzipResponseWriter) startCompression(remain []byte) error { |
| 230 |
// Set the Content-Encoding header based on encoding type. |
| 231 |
switch w.enc { |
| 232 |
case encodingGzip: |
| 233 |
w.Header().Set(contentEncoding, "gzip") |
| 234 |
case encodingZstd: |
| 235 |
w.Header().Set(contentEncoding, "zstd") |
| 236 |
default: |
| 237 |
return w.startPlain() |
| 238 |
} |
| 239 |
|
| 240 |
// if the Content-Length is already set, then calls to Write on compression |
| 241 |
// will fail to set the Content-Length header since its already set |
| 242 |
// See: https://github.com/golang/go/issues/14975. |
| 243 |
w.Header().Del(contentLength) |
| 244 |
|
| 245 |
// Delete Accept-Ranges. |
| 246 |
if !w.keepAcceptRanges { |
| 247 |
w.Header().Del(acceptRanges) |
| 248 |
} |
| 249 |
|
| 250 |
// Suffix ETag with encoding-specific value to avoid cache conflicts. |
| 251 |
if w.suffixETag != "" && !w.dropETag && w.Header().Get(eTag) != "" { |
| 252 |
orig := w.Header().Get(eTag) |
| 253 |
insertPoint := strings.LastIndex(orig, `"`) |
| 254 |
if insertPoint == -1 { |
| 255 |
insertPoint = len(orig) |
| 256 |
} |
| 257 |
suffix := w.suffixETag |
| 258 |
switch w.enc { |
| 259 |
case encodingGzip: |
| 260 |
if !strings.Contains(suffix, "gzip") { |
| 261 |
suffix += "-gzip" |
| 262 |
} |
| 263 |
case encodingZstd: |
| 264 |
if strings.Contains(suffix, "gzip") { |
| 265 |
suffix = strings.Replace(suffix, "gzip", "zstd", 1) |
| 266 |
} else { |
| 267 |
suffix += "-zstd" |
| 268 |
} |
| 269 |
} |
| 270 |
w.Header().Set(eTag, orig[:insertPoint]+suffix+orig[insertPoint:]) |
| 271 |
} |
| 272 |
|
| 273 |
// Delete ETag. |
| 274 |
if w.dropETag { |
| 275 |
w.Header().Del(eTag) |
| 276 |
} |
| 277 |
|
| 278 |
// Write the header to response. |
| 279 |
if w.code != 0 { |
| 280 |
w.ResponseWriter.WriteHeader(w.code) |
| 281 |
// Ensure that no other WriteHeader's happen |
| 282 |
w.code = 0 |
| 283 |
} |
| 284 |
|
| 285 |
// Initialize and flush the buffer into the compressed response if there are any bytes. |
| 286 |
// If there aren't any, we shouldn't initialize it yet because on Close it will |
| 287 |
// write the compression header even if nothing was ever written. |
| 288 |
if len(w.buf) > 0 { |
| 289 |
// Initialize the compression response. |
| 290 |
w.init() |
| 291 |
|
| 292 |
// Set random jitter based on CRC or SHA-256 of current buffer. |
| 293 |
if len(w.randomJitter) > 0 { |
| 294 |
var jitRNG uint32 |
| 295 |
if w.jitterBuffer > 0 { |
| 296 |
// Use only up to "w.jitterBuffer", otherwise the output depends on write sizes. |
| 297 |
// w.buf can grow to wantBuf (max(minSize, 512[, jitterBuffer])), which may exceed jitterBuffer. |
| 298 |
hashBuf := w.buf |
| 299 |
if len(hashBuf) > w.jitterBuffer { |
| 300 |
hashBuf = hashBuf[:w.jitterBuffer] |
| 301 |
} |
| 302 |
if w.sha256Jitter { |
| 303 |
h := sha256.New() |
| 304 |
h.Write(hashBuf) |
| 305 |
if len(remain) > 0 && len(hashBuf) < w.jitterBuffer { |
| 306 |
remain := remain |
| 307 |
if len(remain)+len(hashBuf) > w.jitterBuffer { |
| 308 |
remain = remain[:w.jitterBuffer-len(hashBuf)] |
| 309 |
} |
| 310 |
h.Write(remain) |
| 311 |
} |
| 312 |
var tmp [sha256.Size]byte |
| 313 |
jitRNG = binary.LittleEndian.Uint32(h.Sum(tmp[:0])) |
| 314 |
} else { |
| 315 |
h := crc32.Update(0, castagnoliTable, hashBuf) |
| 316 |
if len(remain) > 0 && len(hashBuf) < w.jitterBuffer { |
| 317 |
remain := remain |
| 318 |
if len(remain)+len(hashBuf) > w.jitterBuffer { |
| 319 |
remain = remain[:w.jitterBuffer-len(hashBuf)] |
| 320 |
} |
| 321 |
h = crc32.Update(h, castagnoliTable, remain) |
| 322 |
} |
| 323 |
jitRNG = bits.RotateLeft32(h, 19) ^ 0xab0755de |
| 324 |
} |
| 325 |
} else { |
| 326 |
// Get from rand.Reader |
| 327 |
var tmp [4]byte |
| 328 |
_, err := rand.Read(tmp[:]) |
| 329 |
if err != nil { |
| 330 |
return fmt.Errorf("gzhttp: %w", err) |
| 331 |
} |
| 332 |
jitRNG = binary.LittleEndian.Uint32(tmp[:]) |
| 333 |
} |
| 334 |
jit := w.randomJitter[:1+jitRNG%uint32(len(w.randomJitter)-1)] |
| 335 |
if w.enc == encodingGzip { |
| 336 |
w.gw.(writer.GzipWriterExt).SetHeader(writer.Header{Comment: jit}) |
| 337 |
} else if w.enc == encodingZstd { |
| 338 |
// Store jitter for zstd to write as skippable frame on Close |
| 339 |
w.zstdJitter = []byte(jit) |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
var n int |
| 344 |
var err error |
| 345 |
if w.gw != nil { |
| 346 |
n, err = w.gw.Write(w.buf) |
| 347 |
} else if w.zw != nil { |
| 348 |
n, err = w.zw.Write(w.buf) |
| 349 |
} |
| 350 |
|
| 351 |
// This should never happen (per io.Writer docs), but if the write didn't |
| 352 |
// accept the entire buffer but returned no specific error, we have no clue |
| 353 |
// what's going on, so abort just to be safe. |
| 354 |
if err == nil && n < len(w.buf) { |
| 355 |
err = io.ErrShortWrite |
| 356 |
} |
| 357 |
w.buf = w.buf[:0] |
| 358 |
return err |
| 359 |
} |
| 360 |
return nil |
| 361 |
} |
| 362 |
|
| 363 |
// startPlain writes to sent bytes and buffer the underlying ResponseWriter without gzip. |
| 364 |
func (w *GzipResponseWriter) startPlain() error { |
| 365 |
w.Header().Del(HeaderNoCompression) |
| 366 |
if w.code != 0 { |
| 367 |
w.ResponseWriter.WriteHeader(w.code) |
| 368 |
// Ensure that no other WriteHeader's happen |
| 369 |
w.code = 0 |
| 370 |
} |
| 371 |
|
| 372 |
w.ignore = true |
| 373 |
// If Write was never called then don't call Write on the underlying ResponseWriter. |
| 374 |
if len(w.buf) == 0 { |
| 375 |
return nil |
| 376 |
} |
| 377 |
n, err := w.ResponseWriter.Write(w.buf) |
| 378 |
// This should never happen (per io.Writer docs), but if the write didn't |
| 379 |
// accept the entire buffer but returned no specific error, we have no clue |
| 380 |
// what's going on, so abort just to be safe. |
| 381 |
if err == nil && n < len(w.buf) { |
| 382 |
err = io.ErrShortWrite |
| 383 |
} |
| 384 |
|
| 385 |
w.buf = w.buf[:0] |
| 386 |
return err |
| 387 |
} |
| 388 |
|
| 389 |
// WriteHeader just saves the response code until close or GZIP effective writes. |
| 390 |
// In the specific case of 1xx status codes, WriteHeader is directly calling the wrapped ResponseWriter. |
| 391 |
func (w *GzipResponseWriter) WriteHeader(code int) { |
| 392 |
// Handle informational headers |
| 393 |
// This is gated to not forward 1xx responses on builds prior to go1.20. |
| 394 |
if code >= 100 && code <= 199 { |
| 395 |
w.ResponseWriter.WriteHeader(code) |
| 396 |
return |
| 397 |
} |
| 398 |
|
| 399 |
if w.code == 0 { |
| 400 |
w.code = code |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
// init grabs a new compression writer from the appropriate pool. |
| 405 |
func (w *GzipResponseWriter) init() { |
| 406 |
switch w.enc { |
| 407 |
case encodingGzip: |
| 408 |
w.gw = w.gwFactory.New(w.ResponseWriter, w.level) |
| 409 |
case encodingZstd: |
| 410 |
w.zw = w.zstdFactory.New(w.ResponseWriter, w.zstdLevel) |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
// bodyAllowedForStatus reports whether a given response status code |
| 415 |
// permits a body. See RFC 7230, section 3.3. |
| 416 |
func bodyAllowedForStatus(status int) bool { |
| 417 |
switch { |
| 418 |
case status >= 100 && status <= 199: |
| 419 |
return false |
| 420 |
case status == 204: |
| 421 |
return false |
| 422 |
case status == 304: |
| 423 |
return false |
| 424 |
} |
| 425 |
return true |
| 426 |
} |
| 427 |
|
| 428 |
// Close will close the compression writer and return it to the pool. |
| 429 |
func (w *GzipResponseWriter) Close() error { |
| 430 |
if w.ignore { |
| 431 |
return nil |
| 432 |
} |
| 433 |
if w.gw == nil && w.zw == nil { |
| 434 |
var ( |
| 435 |
ct = w.Header().Get(contentType) |
| 436 |
ce = w.Header().Get(contentEncoding) |
| 437 |
cr = w.Header().Get(contentRange) |
| 438 |
) |
| 439 |
|
| 440 |
// Detects the response content-type when it does not exist and the response has a body. |
| 441 |
if ct == "" && bodyAllowedForStatus(w.code) && len(w.buf) > 0 { |
| 442 |
ct = http.DetectContentType(w.buf) |
| 443 |
|
| 444 |
// Handles the intended case of setting a nil Content-Type (as for http/server or http/fs) |
| 445 |
// Set the header only if the key does not exist |
| 446 |
if _, ok := w.Header()[contentType]; w.setContentType && !ok { |
| 447 |
w.Header().Set(contentType, ct) |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
if len(w.buf) == 0 || len(w.buf) < w.minSize || len(w.Header()[HeaderNoCompression]) != 0 || ce != "" || cr != "" || !w.contentTypeFilter(ct) { |
| 452 |
// Compression not triggered, write out regular response. |
| 453 |
return w.startPlain() |
| 454 |
} |
| 455 |
err := w.startCompression(nil) |
| 456 |
if err != nil { |
| 457 |
return err |
| 458 |
} |
| 459 |
} |
| 460 |
|
| 461 |
if w.gw != nil { |
| 462 |
err := w.gw.Close() |
| 463 |
w.gw = nil |
| 464 |
return err |
| 465 |
} |
| 466 |
if w.zw != nil { |
| 467 |
err := w.zw.Close() |
| 468 |
w.zw = nil |
| 469 |
if err != nil { |
| 470 |
return err |
| 471 |
} |
| 472 |
// Write zstd jitter as skippable frame (RFC 8878 Section 3.1.2) |
| 473 |
if len(w.zstdJitter) > 0 { |
| 474 |
err = w.writeZstdSkippableFrame(w.zstdJitter) |
| 475 |
w.zstdJitter = nil |
| 476 |
} |
| 477 |
return err |
| 478 |
} |
| 479 |
return nil |
| 480 |
} |
| 481 |
|
| 482 |
// writeZstdSkippableFrame writes a zstd skippable frame containing the given data. |
| 483 |
// Skippable frames are ignored by zstd decoders per RFC 8878. |
| 484 |
func (w *GzipResponseWriter) writeZstdSkippableFrame(data []byte) error { |
| 485 |
// Skippable frame format: |
| 486 |
// Magic_Number: 4 bytes, little-endian, 0x184D2A5? (we use 0x184D2A50) |
| 487 |
// Frame_Size: 4 bytes, little-endian |
| 488 |
// User_Data: Frame_Size bytes |
| 489 |
var header [8]byte |
| 490 |
binary.LittleEndian.PutUint32(header[0:4], 0x184D2A50) |
| 491 |
binary.LittleEndian.PutUint32(header[4:8], uint32(len(data))) |
| 492 |
if _, err := w.ResponseWriter.Write(header[:]); err != nil { |
| 493 |
return err |
| 494 |
} |
| 495 |
_, err := w.ResponseWriter.Write(data) |
| 496 |
return err |
| 497 |
} |
| 498 |
|
| 499 |
// Flush flushes the underlying compression writer and then the underlying |
| 500 |
// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter |
| 501 |
// an http.Flusher. |
| 502 |
// If not enough bytes has been written to determine if we have reached minimum size, |
| 503 |
// this will be ignored. |
| 504 |
// If nothing has been written yet, nothing will be flushed. |
| 505 |
func (w *GzipResponseWriter) Flush() { |
| 506 |
if w.gw == nil && w.zw == nil && !w.ignore { |
| 507 |
if len(w.buf) == 0 { |
| 508 |
// Nothing written yet. |
| 509 |
return |
| 510 |
} |
| 511 |
var ( |
| 512 |
cl, _ = atoi(w.Header().Get(contentLength)) |
| 513 |
ct = w.Header().Get(contentType) |
| 514 |
ce = w.Header().Get(contentEncoding) |
| 515 |
cr = w.Header().Get(contentRange) |
| 516 |
) |
| 517 |
|
| 518 |
// Detects the response content-type when it does not exist and the response has a body. |
| 519 |
if ct == "" && bodyAllowedForStatus(w.code) && len(w.buf) > 0 { |
| 520 |
ct = http.DetectContentType(w.buf) |
| 521 |
|
| 522 |
// Handles the intended case of setting a nil Content-Type (as for http/server or http/fs) |
| 523 |
// Set the header only if the key does not exist |
| 524 |
if _, ok := w.Header()[contentType]; w.setContentType && !ok { |
| 525 |
w.Header().Set(contentType, ct) |
| 526 |
} |
| 527 |
} |
| 528 |
if cl == 0 { |
| 529 |
// Assume minSize. |
| 530 |
cl = w.minSize |
| 531 |
} |
| 532 |
|
| 533 |
// See if we should compress... |
| 534 |
if len(w.Header()[HeaderNoCompression]) == 0 && ce == "" && cr == "" && cl >= w.minSize && w.contentTypeFilter(ct) { |
| 535 |
w.startCompression(nil) |
| 536 |
} else { |
| 537 |
w.startPlain() |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
if w.gw != nil { |
| 542 |
w.gw.Flush() |
| 543 |
} |
| 544 |
if w.zw != nil { |
| 545 |
w.zw.Flush() |
| 546 |
} |
| 547 |
|
| 548 |
if fw, ok := w.ResponseWriter.(http.Flusher); ok { |
| 549 |
fw.Flush() |
| 550 |
} |
| 551 |
} |
| 552 |
|
| 553 |
// Hijack implements http.Hijacker. If the underlying ResponseWriter is a |
| 554 |
// Hijacker, its Hijack method is returned. Otherwise an error is returned. |
| 555 |
func (w *GzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| 556 |
if hj, ok := w.ResponseWriter.(http.Hijacker); ok { |
| 557 |
return hj.Hijack() |
| 558 |
} |
| 559 |
return nil, nil, fmt.Errorf("http.Hijacker interface is not supported") |
| 560 |
} |
| 561 |
|
| 562 |
// verify Hijacker interface implementation |
| 563 |
var _ http.Hijacker = &GzipResponseWriter{} |
| 564 |
|
| 565 |
var onceDefault sync.Once |
| 566 |
var defaultWrapper func(http.Handler) http.HandlerFunc |
| 567 |
|
| 568 |
// GzipHandler allows to easily wrap an http handler with default settings. |
| 569 |
func GzipHandler(h http.Handler) http.HandlerFunc { |
| 570 |
onceDefault.Do(func() { |
| 571 |
var err error |
| 572 |
defaultWrapper, err = NewWrapper() |
| 573 |
if err != nil { |
| 574 |
panic(err) |
| 575 |
} |
| 576 |
}) |
| 577 |
|
| 578 |
return defaultWrapper(h) |
| 579 |
} |
| 580 |
|
| 581 |
var grwPool = sync.Pool{New: func() any { return &GzipResponseWriter{} }} |
| 582 |
|
| 583 |
// NewWrapper returns a reusable wrapper with the supplied options. |
| 584 |
func NewWrapper(opts ...option) (func(http.Handler) http.HandlerFunc, error) { |
| 585 |
c := &config{ |
| 586 |
level: gzip.DefaultCompression, |
| 587 |
minSize: DefaultMinSize, |
| 588 |
writer: writer.GzipWriterFactory{ |
| 589 |
Levels: gzkp.Levels, |
| 590 |
New: gzkp.NewWriter, |
| 591 |
}, |
| 592 |
contentTypes: DefaultContentTypeFilter, |
| 593 |
setContentType: true, |
| 594 |
|
| 595 |
// Zstd defaults |
| 596 |
zstdEnabled: true, |
| 597 |
zstdLevel: int(zstd.SpeedFastest), |
| 598 |
zstdWriter: writer.ZstdWriterFactory{ |
| 599 |
Levels: zstdkp.Levels, |
| 600 |
New: zstdkp.NewWriter, |
| 601 |
}, |
| 602 |
preferZstd: true, |
| 603 |
gzipEnabled: true, |
| 604 |
} |
| 605 |
|
| 606 |
for _, o := range opts { |
| 607 |
o(c) |
| 608 |
} |
| 609 |
|
| 610 |
if err := c.validate(); err != nil { |
| 611 |
return nil, err |
| 612 |
} |
| 613 |
|
| 614 |
return func(h http.Handler) http.HandlerFunc { |
| 615 |
return func(w http.ResponseWriter, r *http.Request) { |
| 616 |
w.Header().Add(vary, acceptEncoding) |
| 617 |
if c.allowCompressedRequests && contentGzip(r) { |
| 618 |
r.Header.Del(contentEncoding) |
| 619 |
r.Body = &gzipReader{body: r.Body} |
| 620 |
} |
| 621 |
|
| 622 |
enc := selectEncoding(r, c.gzipEnabled, c.zstdEnabled, c.preferZstd) |
| 623 |
if enc != encodingNone { |
| 624 |
gw := grwPool.Get().(*GzipResponseWriter) |
| 625 |
*gw = GzipResponseWriter{ |
| 626 |
ResponseWriter: w, |
| 627 |
gwFactory: c.writer, |
| 628 |
level: c.level, |
| 629 |
enc: enc, |
| 630 |
zstdLevel: c.zstdLevel, |
| 631 |
zstdFactory: c.zstdWriter, |
| 632 |
minSize: c.minSize, |
| 633 |
contentTypeFilter: c.contentTypes, |
| 634 |
keepAcceptRanges: c.keepAcceptRanges, |
| 635 |
dropETag: c.dropETag, |
| 636 |
suffixETag: c.suffixETag, |
| 637 |
buf: gw.buf, |
| 638 |
setContentType: c.setContentType, |
| 639 |
randomJitter: c.randomJitter, |
| 640 |
jitterBuffer: c.jitterBuffer, |
| 641 |
sha256Jitter: c.sha256Jitter, |
| 642 |
} |
| 643 |
if len(gw.buf) > 0 { |
| 644 |
gw.buf = gw.buf[:0] |
| 645 |
} |
| 646 |
defer func() { |
| 647 |
gw.Close() |
| 648 |
gw.ResponseWriter = nil |
| 649 |
grwPool.Put(gw) |
| 650 |
}() |
| 651 |
|
| 652 |
if _, ok := w.(http.CloseNotifier); ok { |
| 653 |
gwcn := GzipResponseWriterWithCloseNotify{gw} |
| 654 |
h.ServeHTTP(gwcn, r) |
| 655 |
} else { |
| 656 |
h.ServeHTTP(gw, r) |
| 657 |
} |
| 658 |
w.Header().Del(HeaderNoCompression) |
| 659 |
} else { |
| 660 |
h.ServeHTTP(newNoGzipResponseWriter(w), r) |
| 661 |
w.Header().Del(HeaderNoCompression) |
| 662 |
} |
| 663 |
} |
| 664 |
}, nil |
| 665 |
} |
| 666 |
|
| 667 |
// Parsed representation of one of the inputs to ContentTypes. |
| 668 |
// See https://golang.org/pkg/mime/#ParseMediaType |
| 669 |
type parsedContentType struct { |
| 670 |
mediaType string |
| 671 |
params map[string]string |
| 672 |
} |
| 673 |
|
| 674 |
// equals returns whether this content type matches another content type. |
| 675 |
func (pct parsedContentType) equals(mediaType string, params map[string]string) bool { |
| 676 |
if pct.mediaType != mediaType { |
| 677 |
return false |
| 678 |
} |
| 679 |
// if pct has no params, don't care about other's params |
| 680 |
if len(pct.params) == 0 { |
| 681 |
return true |
| 682 |
} |
| 683 |
|
| 684 |
// if pct has any params, they must be identical to other's. |
| 685 |
if len(pct.params) != len(params) { |
| 686 |
return false |
| 687 |
} |
| 688 |
for k, v := range pct.params { |
| 689 |
if w, ok := params[k]; !ok || v != w { |
| 690 |
return false |
| 691 |
} |
| 692 |
} |
| 693 |
return true |
| 694 |
} |
| 695 |
|
| 696 |
// Used for functional configuration. |
| 697 |
type config struct { |
| 698 |
minSize int |
| 699 |
level int |
| 700 |
writer writer.GzipWriterFactory |
| 701 |
contentTypes func(ct string) bool |
| 702 |
keepAcceptRanges bool |
| 703 |
setContentType bool |
| 704 |
suffixETag string |
| 705 |
dropETag bool |
| 706 |
jitterBuffer int |
| 707 |
randomJitter string |
| 708 |
sha256Jitter bool |
| 709 |
allowCompressedRequests bool |
| 710 |
|
| 711 |
// Zstd support |
| 712 |
zstdEnabled bool |
| 713 |
zstdLevel int |
| 714 |
zstdWriter writer.ZstdWriterFactory |
| 715 |
preferZstd bool |
| 716 |
gzipEnabled bool |
| 717 |
} |
| 718 |
|
| 719 |
func (c *config) validate() error { |
| 720 |
// Validate gzip level if enabled |
| 721 |
if c.gzipEnabled { |
| 722 |
gzMin, gzMax := c.writer.Levels() |
| 723 |
if c.level < gzMin || c.level > gzMax { |
| 724 |
return fmt.Errorf("invalid gzip compression level requested: %d, valid range %d -> %d", c.level, gzMin, gzMax) |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
// Validate zstd level if enabled |
| 729 |
if c.zstdEnabled { |
| 730 |
zMin, zMax := c.zstdWriter.Levels() |
| 731 |
if c.zstdLevel < zMin || c.zstdLevel > zMax { |
| 732 |
return fmt.Errorf("invalid zstd compression level requested: %d, valid range %d -> %d", c.zstdLevel, zMin, zMax) |
| 733 |
} |
| 734 |
} |
| 735 |
|
| 736 |
// At least one encoding must be enabled |
| 737 |
if !c.gzipEnabled && !c.zstdEnabled { |
| 738 |
return errors.New("at least one compression encoding (gzip or zstd) must be enabled") |
| 739 |
} |
| 740 |
|
| 741 |
if c.minSize < 0 { |
| 742 |
return fmt.Errorf("minimum size must be more than zero") |
| 743 |
} |
| 744 |
if len(c.randomJitter) >= math.MaxUint16 { |
| 745 |
return fmt.Errorf("random jitter size exceeded") |
| 746 |
} |
| 747 |
if len(c.randomJitter) > 0 && c.gzipEnabled { |
| 748 |
// Validate gzip writer supports headers (required for gzip jitter). |
| 749 |
// Zstd uses skippable frames and doesn't need this check. |
| 750 |
gzw, ok := c.writer.New(io.Discard, c.level).(writer.GzipWriterExt) |
| 751 |
if !ok { |
| 752 |
return errors.New("the custom compressor does not allow setting headers for random jitter") |
| 753 |
} |
| 754 |
gzw.Close() |
| 755 |
} |
| 756 |
return nil |
| 757 |
} |
| 758 |
|
| 759 |
type option func(c *config) |
| 760 |
|
| 761 |
func MinSize(size int) option { |
| 762 |
return func(c *config) { |
| 763 |
c.minSize = size |
| 764 |
} |
| 765 |
} |
| 766 |
|
| 767 |
// AllowCompressedRequests will enable or disable RFC 7694 compressed requests. |
| 768 |
// By default this is Disabled. |
| 769 |
// See https://datatracker.ietf.org/doc/html/rfc7694 |
| 770 |
func AllowCompressedRequests(b bool) option { |
| 771 |
return func(c *config) { |
| 772 |
c.allowCompressedRequests = b |
| 773 |
} |
| 774 |
} |
| 775 |
|
| 776 |
// CompressionLevel sets the compression level |
| 777 |
func CompressionLevel(level int) option { |
| 778 |
return func(c *config) { |
| 779 |
c.level = level |
| 780 |
} |
| 781 |
} |
| 782 |
|
| 783 |
// SetContentType sets the content type before returning |
| 784 |
// requests, if unset before returning, and it was detected. |
| 785 |
// Default: true. |
| 786 |
func SetContentType(b bool) option { |
| 787 |
return func(c *config) { |
| 788 |
c.setContentType = b |
| 789 |
} |
| 790 |
} |
| 791 |
|
| 792 |
// Implementation changes the implementation of GzipWriter |
| 793 |
// |
| 794 |
// The default implementation is backed by github.com/klauspost/compress |
| 795 |
// To support RandomJitter, the GzipWriterExt must also be |
| 796 |
// supported by the returned writers. |
| 797 |
func Implementation(writer writer.GzipWriterFactory) option { |
| 798 |
return func(c *config) { |
| 799 |
c.writer = writer |
| 800 |
} |
| 801 |
} |
| 802 |
|
| 803 |
// EnableZstd enables or disables zstd compression. |
| 804 |
// Enabled by default. |
| 805 |
func EnableZstd(enable bool) option { |
| 806 |
return func(c *config) { |
| 807 |
c.zstdEnabled = enable |
| 808 |
} |
| 809 |
} |
| 810 |
|
| 811 |
// ZstdCompressionLevel sets the zstd compression level. |
| 812 |
// Levels are: 1=SpeedFastest, 2=SpeedDefault, 3=SpeedBetterCompression, 4=SpeedBestCompression |
| 813 |
// Default is SpeedFastest (1). |
| 814 |
func ZstdCompressionLevel(level int) option { |
| 815 |
return func(c *config) { |
| 816 |
c.zstdLevel = level |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
// ZstdImplementation changes the implementation of ZstdWriter. |
| 821 |
// The default implementation is backed by github.com/klauspost/compress/zstd |
| 822 |
func ZstdImplementation(zw writer.ZstdWriterFactory) option { |
| 823 |
return func(c *config) { |
| 824 |
c.zstdWriter = zw |
| 825 |
} |
| 826 |
} |
| 827 |
|
| 828 |
// PreferZstd sets whether zstd is preferred when both gzip and zstd |
| 829 |
// have equal qvalues in Accept-Encoding. |
| 830 |
// Default is true (prefer zstd). |
| 831 |
func PreferZstd(prefer bool) option { |
| 832 |
return func(c *config) { |
| 833 |
c.preferZstd = prefer |
| 834 |
} |
| 835 |
} |
| 836 |
|
| 837 |
// EnableGzip enables or disables gzip compression. |
| 838 |
// Enabled by default. |
| 839 |
func EnableGzip(enable bool) option { |
| 840 |
return func(c *config) { |
| 841 |
c.gzipEnabled = enable |
| 842 |
} |
| 843 |
} |
| 844 |
|
| 845 |
// ContentTypes specifies a list of content types to compare |
| 846 |
// the Content-Type header to before compressing. If none |
| 847 |
// match, the response will be returned as-is. |
| 848 |
// |
| 849 |
// Content types are compared in a case-insensitive, whitespace-ignored |
| 850 |
// manner. |
| 851 |
// |
| 852 |
// A MIME type without any other directive will match a content type |
| 853 |
// that has the same MIME type, regardless of that content type's other |
| 854 |
// directives. I.e., "text/html" will match both "text/html" and |
| 855 |
// "text/html; charset=utf-8". |
| 856 |
// |
| 857 |
// A MIME type with any other directive will only match a content type |
| 858 |
// that has the same MIME type and other directives. I.e., |
| 859 |
// "text/html; charset=utf-8" will only match "text/html; charset=utf-8". |
| 860 |
// |
| 861 |
// By default common compressed audio, video and archive formats, see DefaultContentTypeFilter. |
| 862 |
// |
| 863 |
// Setting this will override default and any previous Content Type settings. |
| 864 |
func ContentTypes(types []string) option { |
| 865 |
return func(c *config) { |
| 866 |
var contentTypes []parsedContentType |
| 867 |
for _, v := range types { |
| 868 |
mediaType, params, err := mime.ParseMediaType(v) |
| 869 |
if err == nil { |
| 870 |
contentTypes = append(contentTypes, parsedContentType{mediaType, params}) |
| 871 |
} |
| 872 |
} |
| 873 |
c.contentTypes = func(ct string) bool { |
| 874 |
return handleContentType(contentTypes, ct) |
| 875 |
} |
| 876 |
} |
| 877 |
} |
| 878 |
|
| 879 |
// ExceptContentTypes specifies a list of content types to compare |
| 880 |
// the Content-Type header to before compressing. If none |
| 881 |
// match, the response will be compressed. |
| 882 |
// |
| 883 |
// Content types are compared in a case-insensitive, whitespace-ignored |
| 884 |
// manner. |
| 885 |
// |
| 886 |
// A MIME type without any other directive will match a content type |
| 887 |
// that has the same MIME type, regardless of that content type's other |
| 888 |
// directives. I.e., "text/html" will match both "text/html" and |
| 889 |
// "text/html; charset=utf-8". |
| 890 |
// |
| 891 |
// A MIME type with any other directive will only match a content type |
| 892 |
// that has the same MIME type and other directives. I.e., |
| 893 |
// "text/html; charset=utf-8" will only match "text/html; charset=utf-8". |
| 894 |
// |
| 895 |
// By default common compressed audio, video and archive formats, see DefaultContentTypeFilter. |
| 896 |
// |
| 897 |
// Setting this will override default and any previous Content Type settings. |
| 898 |
func ExceptContentTypes(types []string) option { |
| 899 |
return func(c *config) { |
| 900 |
var contentTypes []parsedContentType |
| 901 |
for _, v := range types { |
| 902 |
mediaType, params, err := mime.ParseMediaType(v) |
| 903 |
if err == nil { |
| 904 |
contentTypes = append(contentTypes, parsedContentType{mediaType, params}) |
| 905 |
} |
| 906 |
} |
| 907 |
c.contentTypes = func(ct string) bool { |
| 908 |
return !handleContentType(contentTypes, ct) |
| 909 |
} |
| 910 |
} |
| 911 |
} |
| 912 |
|
| 913 |
// KeepAcceptRanges will keep Accept-Ranges header on gzipped responses. |
| 914 |
// This will likely break ranged requests since that cannot be transparently |
| 915 |
// handled by the filter. |
| 916 |
func KeepAcceptRanges() option { |
| 917 |
return func(c *config) { |
| 918 |
c.keepAcceptRanges = true |
| 919 |
} |
| 920 |
} |
| 921 |
|
| 922 |
// ContentTypeFilter allows adding a custom content type filter. |
| 923 |
// |
| 924 |
// The supplied function must return true/false to indicate if content |
| 925 |
// should be compressed. |
| 926 |
// |
| 927 |
// When called no parsing of the content type 'ct' has been done. |
| 928 |
// It may have been set or auto-detected. |
| 929 |
// |
| 930 |
// Setting this will override default and any previous Content Type settings. |
| 931 |
func ContentTypeFilter(compress func(ct string) bool) option { |
| 932 |
return func(c *config) { |
| 933 |
c.contentTypes = compress |
| 934 |
} |
| 935 |
} |
| 936 |
|
| 937 |
// SuffixETag adds the specified suffix to the ETag header (if it exists) of |
| 938 |
// responses which are compressed. |
| 939 |
// |
| 940 |
// Per [RFC 7232 Section 2.3.3](https://www.rfc-editor.org/rfc/rfc7232#section-2.3.3), |
| 941 |
// the ETag of a compressed response must differ from it's uncompressed version. |
| 942 |
// |
| 943 |
// A suffix such as "-gzip" is sometimes used as a workaround for generating a |
| 944 |
// unique new ETag (see https://bz.apache.org/bugzilla/show_bug.cgi?id=39727). |
| 945 |
func SuffixETag(suffix string) option { |
| 946 |
return func(c *config) { |
| 947 |
c.suffixETag = suffix |
| 948 |
} |
| 949 |
} |
| 950 |
|
| 951 |
// DropETag removes the ETag of responses which are compressed. If DropETag is |
| 952 |
// specified in conjunction with SuffixETag, this option will take precedence |
| 953 |
// and the ETag will be dropped. |
| 954 |
// |
| 955 |
// Per [RFC 7232 Section 2.3.3](https://www.rfc-editor.org/rfc/rfc7232#section-2.3.3), |
| 956 |
// the ETag of a compressed response must differ from it's uncompressed version. |
| 957 |
// |
| 958 |
// This workaround eliminates ETag conflicts between the compressed and |
| 959 |
// uncompressed versions by removing the ETag from the compressed version. |
| 960 |
func DropETag() option { |
| 961 |
return func(c *config) { |
| 962 |
c.dropETag = true |
| 963 |
} |
| 964 |
} |
| 965 |
|
| 966 |
// RandomJitter adds 1->n random bytes to output based on checksum of payload. |
| 967 |
// Specify the amount of input to buffer before applying jitter. |
| 968 |
// This should cover the sensitive part of your response. |
| 969 |
// This can be used to obfuscate the exact compressed size. |
| 970 |
// Specifying 0 will use a buffer size of 64KB. |
| 971 |
// 'paranoid' will use a slower hashing function, that MAY provide more safety. |
| 972 |
// See README.md for more information. |
| 973 |
// If a negative buffer is given, the amount of jitter will not be content dependent. |
| 974 |
// This provides *less* security than applying content based jitter. |
| 975 |
func RandomJitter(n, buffer int, paranoid bool) option { |
| 976 |
return func(c *config) { |
| 977 |
if n > 0 { |
| 978 |
c.sha256Jitter = paranoid |
| 979 |
c.randomJitter = strings.Repeat("Padding-", 1+(n/8))[:n+1] |
| 980 |
c.jitterBuffer = buffer |
| 981 |
if c.jitterBuffer == 0 { |
| 982 |
c.jitterBuffer = 64 << 10 |
| 983 |
} |
| 984 |
} else { |
| 985 |
c.randomJitter = "" |
| 986 |
c.jitterBuffer = 0 |
| 987 |
} |
| 988 |
} |
| 989 |
} |
| 990 |
|
| 991 |
// contentGzip returns true if the given HTTP request indicates that it gzipped. |
| 992 |
func contentGzip(r *http.Request) bool { |
| 993 |
// See more detail in `acceptsGzip` |
| 994 |
return r.Method != http.MethodHead && r.Body != nil && parseEncodingGzip(r.Header.Get(contentEncoding)) > 0 |
| 995 |
} |
| 996 |
|
| 997 |
// acceptsGzip returns true if the given HTTP request indicates that it will |
| 998 |
// accept a gzipped response. |
| 999 |
func acceptsGzip(r *http.Request) bool { |
| 1000 |
// Note that we don't request this for HEAD requests, |
| 1001 |
// due to a bug in nginx: |
| 1002 |
// https://trac.nginx.org/nginx/ticket/358 |
| 1003 |
// https://golang.org/issue/5522 |
| 1004 |
return r.Method != http.MethodHead && parseEncodingGzip(r.Header.Get(acceptEncoding)) > 0 |
| 1005 |
} |
| 1006 |
|
| 1007 |
// selectEncoding determines the best encoding based on Accept-Encoding header. |
| 1008 |
func selectEncoding(r *http.Request, gzipEnabled, zstdEnabled, preferZstd bool) encoding { |
| 1009 |
// Don't compress HEAD requests due to nginx bug. |
| 1010 |
if r.Method == http.MethodHead { |
| 1011 |
return encodingNone |
| 1012 |
} |
| 1013 |
|
| 1014 |
ae := r.Header.Get(acceptEncoding) |
| 1015 |
if ae == "" { |
| 1016 |
return encodingNone |
| 1017 |
} |
| 1018 |
|
| 1019 |
gzipQ := parseEncodingQValue(ae, "gzip") |
| 1020 |
zstdQ := parseEncodingQValue(ae, "zstd") |
| 1021 |
|
| 1022 |
// Neither accepted |
| 1023 |
if (!gzipEnabled || gzipQ <= 0) && (!zstdEnabled || zstdQ <= 0) { |
| 1024 |
return encodingNone |
| 1025 |
} |
| 1026 |
|
| 1027 |
// Only one available |
| 1028 |
if !zstdEnabled || zstdQ <= 0 { |
| 1029 |
if gzipEnabled && gzipQ > 0 { |
| 1030 |
return encodingGzip |
| 1031 |
} |
| 1032 |
return encodingNone |
| 1033 |
} |
| 1034 |
if !gzipEnabled || gzipQ <= 0 { |
| 1035 |
if zstdEnabled && zstdQ > 0 { |
| 1036 |
return encodingZstd |
| 1037 |
} |
| 1038 |
return encodingNone |
| 1039 |
} |
| 1040 |
|
| 1041 |
// Both available - compare qvalues |
| 1042 |
if zstdQ > gzipQ { |
| 1043 |
return encodingZstd |
| 1044 |
} |
| 1045 |
if gzipQ > zstdQ { |
| 1046 |
return encodingGzip |
| 1047 |
} |
| 1048 |
// Equal qvalues - use preference |
| 1049 |
if preferZstd { |
| 1050 |
return encodingZstd |
| 1051 |
} |
| 1052 |
return encodingGzip |
| 1053 |
} |
| 1054 |
|
| 1055 |
// parseEncodingQValue returns the qvalue for a specific encoding. |
| 1056 |
func parseEncodingQValue(header, enc string) float64 { |
| 1057 |
header = strings.TrimSpace(header) |
| 1058 |
for len(header) > 0 { |
| 1059 |
stop := strings.IndexByte(header, ',') |
| 1060 |
if stop < 0 { |
| 1061 |
stop = len(header) |
| 1062 |
} |
| 1063 |
coding, qvalue, _ := parseCoding(header[:stop]) |
| 1064 |
if coding == enc { |
| 1065 |
return qvalue |
| 1066 |
} |
| 1067 |
if stop == len(header) { |
| 1068 |
break |
| 1069 |
} |
| 1070 |
header = header[stop+1:] |
| 1071 |
} |
| 1072 |
return 0 |
| 1073 |
} |
| 1074 |
|
| 1075 |
// returns true if we've been configured to compress the specific content type. |
| 1076 |
func handleContentType(contentTypes []parsedContentType, ct string) bool { |
| 1077 |
// If contentTypes is empty we handle all content types. |
| 1078 |
if len(contentTypes) == 0 { |
| 1079 |
return true |
| 1080 |
} |
| 1081 |
|
| 1082 |
mediaType, params, err := mime.ParseMediaType(ct) |
| 1083 |
if err != nil { |
| 1084 |
return false |
| 1085 |
} |
| 1086 |
|
| 1087 |
for _, c := range contentTypes { |
| 1088 |
if c.equals(mediaType, params) { |
| 1089 |
return true |
| 1090 |
} |
| 1091 |
} |
| 1092 |
|
| 1093 |
return false |
| 1094 |
} |
| 1095 |
|
| 1096 |
// parseEncodingGzip returns the qvalue of gzip compression. |
| 1097 |
func parseEncodingGzip(s string) float64 { |
| 1098 |
s = strings.TrimSpace(s) |
| 1099 |
|
| 1100 |
for len(s) > 0 { |
| 1101 |
stop := strings.IndexByte(s, ',') |
| 1102 |
if stop < 0 { |
| 1103 |
stop = len(s) |
| 1104 |
} |
| 1105 |
coding, qvalue, _ := parseCoding(s[:stop]) |
| 1106 |
|
| 1107 |
if coding == "gzip" { |
| 1108 |
return qvalue |
| 1109 |
} |
| 1110 |
if stop == len(s) { |
| 1111 |
break |
| 1112 |
} |
| 1113 |
s = s[stop+1:] |
| 1114 |
} |
| 1115 |
return 0 |
| 1116 |
} |
| 1117 |
|
| 1118 |
func parseEncodings(s string) (codings, error) { |
| 1119 |
split := strings.Split(s, ",") |
| 1120 |
c := make(codings, len(split)) |
| 1121 |
var e []string |
| 1122 |
|
| 1123 |
for _, ss := range split { |
| 1124 |
coding, qvalue, err := parseCoding(ss) |
| 1125 |
|
| 1126 |
if err != nil { |
| 1127 |
e = append(e, err.Error()) |
| 1128 |
} else { |
| 1129 |
c[coding] = qvalue |
| 1130 |
} |
| 1131 |
} |
| 1132 |
|
| 1133 |
// TODO (adammck): Use a proper multi-error struct, so the individual errors |
| 1134 |
// can be extracted if anyone cares. |
| 1135 |
if len(e) > 0 { |
| 1136 |
return c, fmt.Errorf("errors while parsing encodings: %s", strings.Join(e, ", ")) |
| 1137 |
} |
| 1138 |
|
| 1139 |
return c, nil |
| 1140 |
} |
| 1141 |
|
| 1142 |
var errEmptyEncoding = errors.New("empty content-coding") |
| 1143 |
|
| 1144 |
// parseCoding parses a single coding (content-coding with an optional qvalue), |
| 1145 |
// as might appear in an Accept-Encoding header. It attempts to forgive minor |
| 1146 |
// formatting errors. |
| 1147 |
func parseCoding(s string) (coding string, qvalue float64, err error) { |
| 1148 |
// Avoid splitting if we can... |
| 1149 |
if len(s) == 0 { |
| 1150 |
return "", 0, errEmptyEncoding |
| 1151 |
} |
| 1152 |
if !strings.ContainsRune(s, ';') { |
| 1153 |
coding = strings.ToLower(strings.TrimSpace(s)) |
| 1154 |
if coding == "" { |
| 1155 |
err = errEmptyEncoding |
| 1156 |
} |
| 1157 |
return coding, DefaultQValue, err |
| 1158 |
} |
| 1159 |
qvalue = DefaultQValue |
| 1160 |
for n, part := range strings.Split(s, ";") { |
| 1161 |
part = strings.TrimSpace(part) |
| 1162 |
|
| 1163 |
if n == 0 { |
| 1164 |
coding = strings.ToLower(part) |
| 1165 |
} else if len(part) >= 2 && strings.EqualFold(part[:2], "q=") { |
| 1166 |
qvalue, err = strconv.ParseFloat(part[2:], 64) |
| 1167 |
|
| 1168 |
if qvalue < 0.0 { |
| 1169 |
qvalue = 0.0 |
| 1170 |
} else if qvalue > 1.0 { |
| 1171 |
qvalue = 1.0 |
| 1172 |
} |
| 1173 |
} |
| 1174 |
} |
| 1175 |
|
| 1176 |
if coding == "" { |
| 1177 |
err = errEmptyEncoding |
| 1178 |
} |
| 1179 |
|
| 1180 |
return |
| 1181 |
} |
| 1182 |
|
| 1183 |
// Don't compress any audio/video types. |
| 1184 |
var excludePrefixDefault = []string{"video/", "audio/", "image/jp"} |
| 1185 |
|
| 1186 |
// Skip a bunch of compressed types that contains this string. |
| 1187 |
// Curated by supposedly still active formats on https://en.wikipedia.org/wiki/List_of_archive_formats |
| 1188 |
var excludeContainsDefault = []string{"compress", "zip", "snappy", "lzma", "xz", "zstd", "brotli", "stuffit"} |
| 1189 |
|
| 1190 |
// DefaultContentTypeFilter excludes common compressed audio, video and archive formats. |
| 1191 |
func DefaultContentTypeFilter(ct string) bool { |
| 1192 |
ct = strings.TrimSpace(strings.ToLower(ct)) |
| 1193 |
if ct == "" { |
| 1194 |
return true |
| 1195 |
} |
| 1196 |
for _, s := range excludeContainsDefault { |
| 1197 |
if strings.Contains(ct, s) { |
| 1198 |
return false |
| 1199 |
} |
| 1200 |
} |
| 1201 |
|
| 1202 |
for _, prefix := range excludePrefixDefault { |
| 1203 |
if strings.HasPrefix(ct, prefix) { |
| 1204 |
return false |
| 1205 |
} |
| 1206 |
} |
| 1207 |
return true |
| 1208 |
} |
| 1209 |
|
| 1210 |
// CompressAllContentTypeFilter will compress all mime types. |
| 1211 |
func CompressAllContentTypeFilter(ct string) bool { |
| 1212 |
return true |
| 1213 |
} |
| 1214 |
|
| 1215 |
const intSize = 32 << (^uint(0) >> 63) |
| 1216 |
|
| 1217 |
// atoi is equivalent to ParseInt(s, 10, 0), converted to type int. |
| 1218 |
func atoi(s string) (int, bool) { |
| 1219 |
if len(s) == 0 { |
| 1220 |
return 0, false |
| 1221 |
} |
| 1222 |
sLen := len(s) |
| 1223 |
if intSize == 32 && (0 < sLen && sLen < 10) || |
| 1224 |
intSize == 64 && (0 < sLen && sLen < 19) { |
| 1225 |
// Fast path for small integers that fit int type. |
| 1226 |
s0 := s |
| 1227 |
if s[0] == '-' || s[0] == '+' { |
| 1228 |
s = s[1:] |
| 1229 |
if len(s) < 1 { |
| 1230 |
return 0, false |
| 1231 |
} |
| 1232 |
} |
| 1233 |
|
| 1234 |
n := 0 |
| 1235 |
for _, ch := range []byte(s) { |
| 1236 |
ch -= '0' |
| 1237 |
if ch > 9 { |
| 1238 |
return 0, false |
| 1239 |
} |
| 1240 |
n = n*10 + int(ch) |
| 1241 |
} |
| 1242 |
if s0[0] == '-' { |
| 1243 |
n = -n |
| 1244 |
} |
| 1245 |
return n, true |
| 1246 |
} |
| 1247 |
|
| 1248 |
// Slow path for invalid, big, or underscored integers. |
| 1249 |
i64, err := strconv.ParseInt(s, 10, 0) |
| 1250 |
return int(i64), err == nil |
| 1251 |
} |
| 1252 |
|
| 1253 |
type unwrapper interface { |
| 1254 |
Unwrap() http.ResponseWriter |
| 1255 |
} |
| 1256 |
|
| 1257 |
// newNoGzipResponseWriter will return a response writer that |
| 1258 |
// cleans up compression artifacts. |
| 1259 |
// Depending on whether http.Hijacker is supported the returned will as well. |
| 1260 |
func newNoGzipResponseWriter(w http.ResponseWriter) http.ResponseWriter { |
| 1261 |
n := &NoGzipResponseWriter{ResponseWriter: w} |
| 1262 |
if hj, ok := w.(http.Hijacker); ok { |
| 1263 |
x := struct { |
| 1264 |
http.ResponseWriter |
| 1265 |
http.Hijacker |
| 1266 |
http.Flusher |
| 1267 |
unwrapper |
| 1268 |
}{ |
| 1269 |
ResponseWriter: n, |
| 1270 |
Hijacker: hj, |
| 1271 |
Flusher: n, |
| 1272 |
unwrapper: n, |
| 1273 |
} |
| 1274 |
return x |
| 1275 |
} |
| 1276 |
|
| 1277 |
return n |
| 1278 |
} |
| 1279 |
|
| 1280 |
// NoGzipResponseWriter filters out HeaderNoCompression. |
| 1281 |
type NoGzipResponseWriter struct { |
| 1282 |
http.ResponseWriter |
| 1283 |
hdrCleaned bool |
| 1284 |
} |
| 1285 |
|
| 1286 |
func (n *NoGzipResponseWriter) CloseNotify() <-chan bool { |
| 1287 |
if cn, ok := n.ResponseWriter.(http.CloseNotifier); ok { |
| 1288 |
return cn.CloseNotify() |
| 1289 |
} |
| 1290 |
return nil |
| 1291 |
} |
| 1292 |
|
| 1293 |
func (n *NoGzipResponseWriter) Flush() { |
| 1294 |
if !n.hdrCleaned { |
| 1295 |
n.ResponseWriter.Header().Del(HeaderNoCompression) |
| 1296 |
n.hdrCleaned = true |
| 1297 |
} |
| 1298 |
if f, ok := n.ResponseWriter.(http.Flusher); ok { |
| 1299 |
f.Flush() |
| 1300 |
} |
| 1301 |
} |
| 1302 |
|
| 1303 |
func (n *NoGzipResponseWriter) Header() http.Header { |
| 1304 |
return n.ResponseWriter.Header() |
| 1305 |
} |
| 1306 |
|
| 1307 |
func (n *NoGzipResponseWriter) Write(bytes []byte) (int, error) { |
| 1308 |
if !n.hdrCleaned { |
| 1309 |
n.ResponseWriter.Header().Del(HeaderNoCompression) |
| 1310 |
n.hdrCleaned = true |
| 1311 |
} |
| 1312 |
return n.ResponseWriter.Write(bytes) |
| 1313 |
} |
| 1314 |
|
| 1315 |
func (n *NoGzipResponseWriter) WriteHeader(statusCode int) { |
| 1316 |
if !n.hdrCleaned { |
| 1317 |
n.ResponseWriter.Header().Del(HeaderNoCompression) |
| 1318 |
n.hdrCleaned = true |
| 1319 |
} |
| 1320 |
n.ResponseWriter.WriteHeader(statusCode) |
| 1321 |
} |
| 1322 |
|
| 1323 |
func (n *NoGzipResponseWriter) Unwrap() http.ResponseWriter { |
| 1324 |
return n.ResponseWriter |
| 1325 |
} |