Skip to content

Commit

Permalink
fix(compress): correct content encoding negotiation
Browse files Browse the repository at this point in the history
Signed-off-by: xkx <[email protected]>
  • Loading branch information
xkx9431 committed Nov 20, 2024
1 parent 6c94439 commit ac3c299
Showing 1 changed file with 35 additions and 27 deletions.
62 changes: 35 additions & 27 deletions lib/util/lifted/influx/httpd/handler_compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,36 +37,44 @@ type lazyCompressResponseWriter struct {
func compressFilter(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var writer io.Writer = w
contentEncoding := r.Header.Get("Content-Encoding")
switch {
case strings.Contains(contentEncoding, "gzip"):
gz := getGzipWriter(w)
defer gz.Close()
writer = gz
w.Header().Set("Content-Encoding", "gzip")
case strings.Contains(contentEncoding, "zstd"):
enc := getZstdWriter(w)
defer enc.Close()
writer = enc
w.Header().Set("Content-Encoding", "zstd")
default:
inner.ServeHTTP(w, r)
return
}

compressEnabledWriter := &lazyCompressResponseWriter{ResponseWriter: w, Writer: writer}

if f, ok := w.(http.Flusher); ok {
compressEnabledWriter.Flusher = f
acceptEncoding := r.Header.Get("Accept-Encoding")
encodings := strings.Split(acceptEncoding, ",")

// if mutliple encodings are supported, server will use the first one that is supported
for _, encoding := range encodings {
encoding = strings.TrimSpace(encoding)
switch encoding {
case "gzip":
gz := getGzipWriter(w)
defer gz.Close()
writer = gz
w.Header().Set("Content-Encoding", "gzip")
break
case "zstd":
enc := getZstdWriter(w)
defer enc.Close()
writer = enc
w.Header().Set("Content-Encoding", "zstd")
break
}
if writer != w {
break
}
}

if cn, ok := w.(http.CloseNotifier); ok {
compressEnabledWriter.CloseNotifier = cn
if writer == w {
inner.ServeHTTP(w, r)
} else {
compressEnabledWriter := &lazyCompressResponseWriter{ResponseWriter: w, Writer: writer}
if f, ok := w.(http.Flusher); ok {
compressEnabledWriter.Flusher = f
}
if cn, ok := w.(http.CloseNotifier); ok {
compressEnabledWriter.CloseNotifier = cn
}
defer compressEnabledWriter.Close()
inner.ServeHTTP(compressEnabledWriter, r)
}

defer compressEnabledWriter.Close()

inner.ServeHTTP(compressEnabledWriter, r)
})
}

Expand Down

0 comments on commit ac3c299

Please sign in to comment.