Skip to main content

⬇️ Gzip

Gzip wraps around your current Response and compresses all the data written to it, if the client has specified gzip in the Accept-Encoding header.

func Gzip(response Response) Response {
r := &gzipMiddleware{response}
return r
}

type gzipMiddleware struct {
response Response
}

type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}

func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}

func (j gzipMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get(header.RequestAcceptEncoding), "gzip") {
j.response.ServeHTTP(rw, r)
return
}

gz := gzip.NewWriter(rw)
defer gz.Close()

rw.Header().Set(header.ContentEncoding, "gzip")

var responseWriter http.ResponseWriter = gzipResponseWriter{Writer: gz, ResponseWriter: rw}
j.response.ServeHTTP(responseWriter, r)
}