Skip to content

Instantly share code, notes, and snippets.

@jakobii
Last active November 14, 2019 21:15
Show Gist options
  • Save jakobii/e0ded76426dd6483edf707ae0c5dac5f to your computer and use it in GitHub Desktop.
Save jakobii/e0ded76426dd6483edf707ae0c5dac5f to your computer and use it in GitHub Desktop.
gzip golang http responses
//https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
func writeOptimizedHttpResponse(w http.ResponseWriter, r *http.Request, b []byte, contentType string) {
w.Header().Set("Content-Type", contentType)
encodings := r.Header.Get("Accept-Encoding")
switch {
case strings.Contains(encodings, "gzip"):
w.Header().Set("Content-Encoding", "gzip")
//w.Header().Del("Content-Length")
zipper := gzip.NewWriter(w)
defer zipper.Close()
zipper.Write(b)
//case compress:
//case deflate:
//case br:
default:
//identity
fmt.Fprint(w, b)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment