github.com/Jeffail/benthos/v3@v3.65.0/lib/util/http/gzip_handler.go (about) 1 package http 2 3 import ( 4 "compress/gzip" 5 "io" 6 "net/http" 7 "strings" 8 ) 9 10 //------------------------------------------------------------------------------ 11 12 type gzipResponseWriter struct { 13 io.Writer 14 http.ResponseWriter 15 } 16 17 func (w gzipResponseWriter) Write(b []byte) (int, error) { 18 if w.Header().Get("Content-Type") == "" { 19 // If no content type, apply sniffing algorithm to un-gzipped body. 20 w.Header().Set("Content-Type", http.DetectContentType(b)) 21 } 22 return w.Writer.Write(b) 23 } 24 25 // GzipHandler wraps a handlerfunc with a handler that automatically Gzips 26 // outbound messages. 27 func GzipHandler(fn http.HandlerFunc) http.HandlerFunc { 28 return func(w http.ResponseWriter, r *http.Request) { 29 if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { 30 fn(w, r) 31 return 32 } 33 w.Header().Set("Content-Encoding", "gzip") 34 gz := gzip.NewWriter(w) 35 defer gz.Close() 36 gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w} 37 fn(gzr, r) 38 } 39 } 40 41 //------------------------------------------------------------------------------