traefik/old/middlewares/compress.go

34 lines
819 B
Go
Raw Normal View History

2016-09-28 21:07:06 +00:00
package middlewares
import (
2017-07-13 15:56:01 +00:00
"compress/gzip"
2016-09-28 21:07:06 +00:00
"net/http"
2017-11-10 13:12:02 +00:00
"strings"
"github.com/NYTimes/gziphandler"
2018-11-14 09:18:03 +00:00
"github.com/containous/traefik/old/log"
2017-06-06 23:02:02 +00:00
)
2018-08-02 15:14:03 +00:00
// Compress is a middleware that allows to compress the response
2017-06-06 23:02:02 +00:00
type Compress struct{}
2016-09-28 21:07:06 +00:00
2018-07-03 08:02:03 +00:00
// ServeHTTP is a function used by Negroni
2016-09-28 21:29:27 +00:00
func (c *Compress) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
2017-11-10 13:12:02 +00:00
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/grpc") {
next.ServeHTTP(rw, r)
} else {
gzipHandler(next).ServeHTTP(rw, r)
}
2017-06-06 23:02:02 +00:00
}
2017-07-13 15:56:01 +00:00
func gzipHandler(h http.Handler) http.Handler {
2017-08-21 09:10:03 +00:00
wrapper, err := gziphandler.GzipHandlerWithOpts(
gziphandler.CompressionLevel(gzip.DefaultCompression),
gziphandler.MinSize(gziphandler.DefaultMinSize))
2017-07-13 15:56:01 +00:00
if err != nil {
log.Error(err)
}
return wrapper(h)
2016-09-28 21:07:06 +00:00
}