traefik/middlewares/compress.go

32 lines
823 B
Go
Raw Normal View History

2016-09-28 21:07:06 +00:00
package middlewares
import (
"net/http"
"github.com/NYTimes/gziphandler"
2016-09-28 21:07:06 +00:00
)
2017-06-06 23:02:02 +00:00
const (
contentEncodingHeader = "Content-Encoding"
)
// 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-06-06 23:02:02 +00:00
if isEncoded(r.Header) {
next.ServeHTTP(rw, r)
} else {
newGzipHandler := gziphandler.GzipHandler(next)
newGzipHandler.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"
2016-09-28 21:07:06 +00:00
}