github.com/pbberlin/go-pwa@v0.0.0-20220328105622-7c26e0ca1ab8/pkg/gziphandlermin/gzip-handler-min.go (about) 1 // package gziphandler dynamically compresses files and serves them 2 package gziphandlermin 3 4 import ( 5 "compress/gzip" 6 "io" 7 "net/http" 8 "strings" 9 ) 10 11 type gzipResponseWriter struct { 12 io.Writer 13 http.ResponseWriter 14 } 15 16 func (w gzipResponseWriter) Write(b []byte) (int, error) { 17 return w.Writer.Write(b) 18 } 19 20 func MakeGzipHandler(fn http.HandlerFunc) http.HandlerFunc { 21 return func(w http.ResponseWriter, r *http.Request) { 22 if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { 23 fn(w, r) 24 return 25 } 26 w.Header().Set("Content-Encoding", "gzip") 27 gz := gzip.NewWriter(w) 28 defer gz.Close() 29 gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w} 30 fn(gzr, r) 31 } 32 } 33 34 func handler(w http.ResponseWriter, r *http.Request) { 35 w.Header().Set("Content-Type", "text/plain") 36 w.Write([]byte("This is a test.")) 37 } 38 39 func main() { 40 http.ListenAndServe(":1113", MakeGzipHandler(handler)) 41 }