Skip to content

Commit

Permalink
Add get/put helpers for gzip writer pool
Browse files Browse the repository at this point in the history
  • Loading branch information
akshayjshah committed Feb 28, 2022
1 parent e3d008c commit 46cab7f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
12 changes: 12 additions & 0 deletions gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ var gzWriterPool = sync.Pool{
},
}

func getGzipWriter(w io.Writer) *gzip.Writer {
gw := gzWriterPool.Get().(*gzip.Writer)
gw.Reset(w)
return gw
}

func putGzipWriter(gw *gzip.Writer) {
gw.Close() // close if we haven't already
gw.Reset(io.Discard) // don't keep references
gzWriterPool.Put(gw)
}

// Verify we're implementing these interfaces at compile time.
var (
_ http.ResponseWriter = &gzipResponseWriter{}
Expand Down
9 changes: 2 additions & 7 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,14 +318,9 @@ func (h *Handler) writeResultTwirp(ctx context.Context, w http.ResponseWriter, s
// ResponseWriter.
if spec.ResponseCompression == CompressionGzip && w.Header().Get("Content-Encoding") == "" {
w.Header().Set("Content-Encoding", "gzip")
gw := gzWriterPool.Get().(*gzip.Writer)
gw.Reset(w)
gw := getGzipWriter(w)
defer putGzipWriter(gw)
w = &gzipResponseWriter{ResponseWriter: w, gw: gw}
defer func() {
gw.Close() // close if we haven't already
gw.Reset(io.Discard) // don't keep references
gzWriterPool.Put(gw)
}()
}
if err != nil {
// Twirp always writes errors as JSON.
Expand Down

0 comments on commit 46cab7f

Please sign in to comment.