diff --git a/handler.go b/handler.go index 067578e..7bc51e3 100644 --- a/handler.go +++ b/handler.go @@ -6,8 +6,6 @@ import ( "net/http" "path/filepath" "strings" - "sync" - "time" "github.com/gin-gonic/gin" "github.com/klauspost/compress/gzip" @@ -15,21 +13,13 @@ import ( 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) @@ -37,27 +27,6 @@ func newGzipHandler(level int, options ...Option) *gzipHandler { 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) @@ -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())) @@ -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 +}