Skip to content

Instantly share code, notes, and snippets.

@bryfry
Last active August 28, 2023 09:23
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save bryfry/09a650eb8aac0fb76c24 to your computer and use it in GitHub Desktop.
Save bryfry/09a650eb8aac0fb76c24 to your computer and use it in GitHub Desktop.
Idiomatic golang net/http gzip transparent compression (works with Alice)
package main
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
// Gzip Compression
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func Gzip(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
handler.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
handler.ServeHTTP(gzw, r)
})
}
@lyda
Copy link

lyda commented Jun 23, 2019

In the case of serving a file, would it be an option to look for an already compressed version of the file?

@jftuga
Copy link

jftuga commented Apr 16, 2020

For max compression:

gzip.NewWriterLevel(w, gzip.BestCompression)

@cli-ish
Copy link

cli-ish commented Apr 29, 2022

Content negotiation is overrated. Make way for CONTENT DICTATORSHIP!

Pure gold, was just seeking for a solution and found this 😄

@TelephoneTan
Copy link

TelephoneTan commented Sep 1, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment