fix: double compression.

This commit is contained in:
Fernandez Ludovic 2017-07-13 17:56:01 +02:00 committed by Ludovic Fernandez
parent 98b52d1f54
commit 36ee69609e
6 changed files with 198 additions and 61 deletions

View file

@ -1,13 +1,11 @@
package middlewares
import (
"compress/gzip"
"net/http"
"github.com/NYTimes/gziphandler"
)
const (
contentEncodingHeader = "Content-Encoding"
"github.com/containous/traefik/log"
)
// Compress is a middleware that allows redirection
@ -15,17 +13,13 @@ type Compress struct{}
// ServerHTTP is a function used by Negroni
func (c *Compress) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if isEncoded(r.Header) {
next.ServeHTTP(rw, r)
} else {
newGzipHandler := gziphandler.GzipHandler(next)
newGzipHandler.ServeHTTP(rw, r)
}
gzipHandler(next).ServeHTTP(rw, r)
}
func isEncoded(headers http.Header) bool {
header := headers.Get(contentEncodingHeader)
// According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding,
// content is not encoded if the header 'Content-Encoding' is empty or equals to 'identity'.
return header != "" && header != "identity"
func gzipHandler(h http.Handler) http.Handler {
wrapper, err := gziphandler.NewGzipHandler(gzip.DefaultCompression, gziphandler.DefaultMinSize, &gziphandler.GzipResponseWriterWrapper{})
if err != nil {
log.Error(err)
}
return wrapper(h)
}