traefik/old/middlewares/compress.go

34 lines
819 B
Go
Raw Normal View History

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