From 455a570e9c01687d07fd86c908bbcb2ebc2eefd6 Mon Sep 17 00:00:00 2001 From: Barna Csorogi Date: Fri, 31 Aug 2018 23:28:46 +0800 Subject: [PATCH] decompress brotli payload before minifying --- transcoder/zip.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/transcoder/zip.go b/transcoder/zip.go index 70c2b99..629bbcc 100644 --- a/transcoder/zip.go +++ b/transcoder/zip.go @@ -2,17 +2,19 @@ package transcoder import ( "compress/gzip" - "github.com/barnacs/compy/proxy" - brotlienc "gopkg.in/kothar/brotli-go.v0/enc" "net/http" "strings" + + "github.com/barnacs/compy/proxy" + brotlidec "gopkg.in/kothar/brotli-go.v0/dec" + brotlienc "gopkg.in/kothar/brotli-go.v0/enc" ) type Zip struct { proxy.Transcoder BrotliCompressionLevel int GzipCompressionLevel int - SkipGzipped bool + SkipCompressed bool } func (t *Zip) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, headers http.Header) error { @@ -28,7 +30,7 @@ func (t *Zip) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, header } // always gunzip if the client supports Brotli - if r.Header().Get("Content-Encoding") == "gzip" && (shouldBrotli || !t.SkipGzipped) { + if r.Header().Get("Content-Encoding") == "gzip" && (shouldBrotli || !t.SkipCompressed) { gzr, err := gzip.NewReader(r.Reader) if err != nil { return err @@ -39,6 +41,14 @@ func (t *Zip) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, header w.Header().Del("Content-Encoding") } + if r.Header().Get("Content-Encoding") == "br" && !t.SkipCompressed { + brr := brotlidec.NewBrotliReader(r.Reader) + defer brr.Close() + r.Reader = brr + r.Header().Del("Content-Encoding") + w.Header().Del("Content-Encoding") + } + if shouldBrotli && compress(r) { params := brotlienc.NewBrotliParams() params.SetQuality(t.BrotliCompressionLevel)