compy/transcoder/gzip.go

51 lines
1.1 KiB
Go
Raw Normal View History

2015-03-28 22:07:40 +00:00
package transcoder
import (
"compress/gzip"
"github.com/barnacs/compy/proxy"
"net/http"
"strings"
2015-03-28 22:07:40 +00:00
)
type Gzip struct {
proxy.Transcoder
SkipGzipped bool
}
func (t *Gzip) Transcode(w *proxy.ResponseWriter, r *proxy.ResponseReader, headers http.Header) error {
2015-03-28 22:07:40 +00:00
if t.decompress(r) {
gzr, err := gzip.NewReader(r.Reader)
if err != nil {
return err
}
defer gzr.Close()
r.Reader = gzr
r.Header().Del("Content-Encoding")
w.Header().Del("Content-Encoding")
}
shouldGzip := false
for _, v := range strings.Split(headers.Get("Accept-Encoding"), ", ") {
if strings.SplitN(v, ";", 2)[0] == "gzip" {
shouldGzip = true
break
}
}
if shouldGzip && compress(r) {
2015-03-28 22:07:40 +00:00
gzw := gzip.NewWriter(w.Writer)
defer gzw.Flush()
w.Writer = gzw
w.Header().Set("Content-Encoding", "gzip")
}
return t.Transcoder.Transcode(w, r, headers)
2015-03-28 22:07:40 +00:00
}
func (t *Gzip) decompress(r *proxy.ResponseReader) bool {
return !t.SkipGzipped && r.Header().Get("Content-Encoding") == "gzip"
}
func compress(r *proxy.ResponseReader) bool {
return r.Header().Get("Content-Encoding") == ""
}