Skip to content

Instantly share code, notes, and snippets.

@CJEnright
Last active March 15, 2026 16:00
Show Gist options
  • Select an option

  • Save CJEnright/bc2d8b8dc0c1389a9feeddb110f822d7 to your computer and use it in GitHub Desktop.

Select an option

Save CJEnright/bc2d8b8dc0c1389a9feeddb110f822d7 to your computer and use it in GitHub Desktop.

Revisions

  1. CJEnright revised this gist Oct 10, 2018. No changes.
  2. CJEnright revised this gist Oct 10, 2018. No changes.
  3. CJEnright renamed this gist Oct 10, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. CJEnright created this gist Oct 10, 2018.
    50 changes: 50 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    package main

    import (
    "net/http"
    "compress/gzip"
    "io/ioutil"
    "strings"
    "sync"
    "io"
    )

    var gzPool = sync.Pool {
    New: func() interface{} {
    w := gzip.NewWriter(ioutil.Discard)
    return w
    },
    }

    type gzipResponseWriter struct {
    io.Writer
    http.ResponseWriter
    }

    func (w *gzipResponseWriter) WriteHeader(status int) {
    w.Header().Del("Content-Length")
    w.ResponseWriter.WriteHeader(status)
    }

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

    func Gzip(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
    next.ServeHTTP(w, r)
    return
    }

    w.Header().Set("Content-Encoding", "gzip")

    gz := gzPool.Get().(*gzip.Writer)
    defer gzPool.Put(gz)

    gz.Reset(w)
    defer gz.Close()

    next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
    })
    }