diff --git a/gzip.go b/gzip.go index af78611..0ecd0b3 100644 --- a/gzip.go +++ b/gzip.go @@ -31,8 +31,8 @@ var serveGzip = func(w http.ResponseWriter, r *http.Request, c martini.Context, headers.Set(HeaderContentEncoding, "gzip") headers.Set(HeaderVary, HeaderAcceptEncoding) - gz := gzip.NewWriter(w) - defer gz.Close() + gz := getGzip(w, options.CompressionLevel) + defer putGzip(gz) gzw := gzipResponseWriter{gz, w.(martini.ResponseWriter)} c.MapTo(gzw, (*http.ResponseWriter)(nil)) @@ -59,12 +59,12 @@ func All(options ...Options) martini.Handler { func prepareOptions(options []Options) Options { var opt Options - if len(options) > 0 { - opt = options[0] - } - if !isCompressionLevelValid(opt.CompressionLevel) { - opt.CompressionLevel = DefaultCompression - } + if len(options) > 0 { + opt = options[0] + } + if !isCompressionLevelValid(opt.CompressionLevel) { + opt.CompressionLevel = DefaultCompression + } return opt } diff --git a/pool.go b/pool.go new file mode 100644 index 0000000..f2f7d05 --- /dev/null +++ b/pool.go @@ -0,0 +1,26 @@ +package gzip + +import ( + "compress/gzip" + "io" + "sync" +) + +var ( + gzipBuffers sync.Pool +) + +func getGzip(dst io.Writer, level int) (w *gzip.Writer) { + if gz := gzipBuffers.Get(); gz != nil { + w = gz.(*gzip.Writer) + w.Reset(dst) + } else { + w, _ = gzip.NewWriterLevel(dst, level) + } + return +} + +func putGzip(gz *gzip.Writer) { + gz.Close() + gzipBuffers.Put(gz) +} diff --git a/wercker.yml b/wercker.yml index f8bf918..41d2c52 100644 --- a/wercker.yml +++ b/wercker.yml @@ -1 +1 @@ -box: wercker/golang@1.1.1 \ No newline at end of file +box: wercker/golang