Skip to content

Commit

Permalink
review: do not use gzip pool
Browse files Browse the repository at this point in the history
  • Loading branch information
thekondor committed Oct 21, 2022
1 parent 34a8c5e commit c4398b4
Showing 1 changed file with 12 additions and 40 deletions.
52 changes: 12 additions & 40 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,58 +6,27 @@ import (
"net/http"
"path/filepath"
"strings"
"sync"
"time"

"github.com/gin-gonic/gin"
"github.com/klauspost/compress/gzip"
)

type gzipHandler struct {
*Options
gzPool sync.Pool
gzipLevel int
}

func newGzipHandler(level int, options ...Option) *gzipHandler {
handler := &gzipHandler{
Options: DefaultOptions,
gzPool: sync.Pool{
New: func() interface{} {
gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
if err != nil {
panic(err)
}
return gz
},
},
Options: DefaultOptions,
gzipLevel: level,
}
for _, setter := range options {
setter(handler.Options)
}
return handler
}

func (g *gzipHandler) scheduleTriggerOnContextDone(done <-chan struct{}, cb func()) {
if done == nil {
return
}

go func(doneCh <-chan struct{}) {
deadline := time.NewTicker(10 * time.Minute)
defer deadline.Stop()
for {
select {
case <-doneCh:
break
case <-deadline.C:
break
}
}

cb()
}(done)
}

func (g *gzipHandler) Handle(c *gin.Context) {
if fn := g.DecompressFn; fn != nil && c.Request.Header.Get("Content-Encoding") == "gzip" {
fn(c)
Expand All @@ -67,18 +36,13 @@ func (g *gzipHandler) Handle(c *gin.Context) {
return
}

gz := g.gzPool.Get().(*gzip.Writer)
gz := g.mustNewGzipWriter()
gz.Reset(c.Writer)

c.Header("Content-Encoding", "gzip")
c.Header("Vary", "Accept-Encoding")
c.Writer = &gzipWriter{ResponseWriter: c.Writer, writer: gz}

g.scheduleTriggerOnContextDone(c.Request.Context().Done(), func() {
gz.Reset(ioutil.Discard)
g.gzPool.Put(gz)
})

defer func() {
gz.Close()
c.Header("Content-Length", fmt.Sprint(c.Writer.Size()))
Expand Down Expand Up @@ -108,3 +72,11 @@ func (g *gzipHandler) isPathExcluded(path string) bool {
g.ExcludedPaths.Contains(path) ||
g.ExcludedPathesRegexs.Contains(path)
}

func (g *gzipHandler) mustNewGzipWriter() *gzip.Writer {
gz, err := gzip.NewWriterLevel(ioutil.Discard, g.gzipLevel)
if err != nil {
panic(err)
}
return gz
}

0 comments on commit c4398b4

Please sign in to comment.