traefik/middlewares/compress.go

34 lines
803 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-14 15:48:03 +00:00
"strings"
"github.com/NYTimes/gziphandler"
2017-07-13 15:56:01 +00:00
"github.com/containous/traefik/log"
2017-06-06 23:02:02 +00:00
)
// Compress is a middleware that allows redirection
type Compress struct{}
2016-09-28 21:07:06 +00:00
2017-06-06 23:02:02 +00:00
// ServerHTTP 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-14 15:48:03 +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
}