decompress brotli payload before minifying

This commit is contained in:
Barna Csorogi 2018-08-31 23:28:46 +08:00
parent d3a5129f1f
commit 455a570e9c

View file

@ -2,17 +2,19 @@ package transcoder
import ( import (
"compress/gzip" "compress/gzip"
"github.com/barnacs/compy/proxy"
brotlienc "gopkg.in/kothar/brotli-go.v0/enc"
"net/http" "net/http"
"strings" "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 { type Zip struct {
proxy.Transcoder proxy.Transcoder
BrotliCompressionLevel int BrotliCompressionLevel int
GzipCompressionLevel int GzipCompressionLevel int
SkipGzipped bool SkipCompressed bool
} }
func (t *Zip) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, headers http.Header) error { 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 // 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) gzr, err := gzip.NewReader(r.Reader)
if err != nil { if err != nil {
return err return err
@ -39,6 +41,14 @@ func (t *Zip) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, header
w.Header().Del("Content-Encoding") 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) { if shouldBrotli && compress(r) {
params := brotlienc.NewBrotliParams() params := brotlienc.NewBrotliParams()
params.SetQuality(t.BrotliCompressionLevel) params.SetQuality(t.BrotliCompressionLevel)