| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"compress/gzip" |
| 5 |
"io" |
| 6 |
"net/http" |
| 7 |
"strings" |
| 8 |
"sync" |
| 9 |
) |
| 10 |
|
| 11 |
// Gzip is a HTTP middleware to transparently compress responses using gzip. |
| 12 |
// Original code from https://gist.github.com/CJEnright/bc2d8b8dc0c1389a9feeddb110f822d7 (MIT) |
| 13 |
func Gzip(next http.Handler) http.Handler { |
| 14 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 15 |
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { |
| 16 |
next.ServeHTTP(w, r) |
| 17 |
return |
| 18 |
} |
| 19 |
w.Header().Set("Content-Encoding", "gzip") |
| 20 |
|
| 21 |
gz := gzPool.Get().(*gzip.Writer) |
| 22 |
defer gzPool.Put(gz) |
| 23 |
|
| 24 |
gz.Reset(w) |
| 25 |
defer gz.Close() |
| 26 |
|
| 27 |
r.Header.Del("Accept-Encoding") // prevent double-gzipping |
| 28 |
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r) |
| 29 |
}) |
| 30 |
} |
| 31 |
|
| 32 |
var gzPool = sync.Pool{ |
| 33 |
New: func() any { |
| 34 |
w := gzip.NewWriter(io.Discard) |
| 35 |
return w |
| 36 |
}, |
| 37 |
} |
| 38 |
|
| 39 |
type gzipResponseWriter struct { |
| 40 |
io.Writer |
| 41 |
http.ResponseWriter |
| 42 |
} |
| 43 |
|
| 44 |
func (w *gzipResponseWriter) WriteHeader(status int) { |
| 45 |
w.Header().Del("Content-Length") |
| 46 |
w.ResponseWriter.WriteHeader(status) |
| 47 |
} |
| 48 |
|
| 49 |
func (w *gzipResponseWriter) Write(b []byte) (int, error) { |
| 50 |
return w.Writer.Write(b) |
| 51 |
} |