traefik/pkg/middlewares/compress/compress.go

60 lines
1.5 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package compress
import (
"compress/gzip"
"context"
"net/http"
"strings"
"github.com/NYTimes/gziphandler"
2019-09-13 17:28:04 +00:00
"github.com/containous/traefik/v2/pkg/log"
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/middlewares"
"github.com/containous/traefik/v2/pkg/tracing"
2018-11-14 09:18:03 +00:00
"github.com/opentracing/opentracing-go/ext"
)
const (
typeName = "Compress"
)
// Compress is a middleware that allows to compress the response.
type compress struct {
next http.Handler
name string
}
// New creates a new compress middleware.
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
2019-09-13 17:28:04 +00:00
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
2018-11-14 09:18:03 +00:00
return &compress{
next: next,
name: name,
}, nil
}
func (c *compress) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
contentType := req.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/grpc") {
c.next.ServeHTTP(rw, req)
} else {
2019-09-13 17:28:04 +00:00
ctx := middlewares.GetLoggerCtx(req.Context(), c.name, typeName)
gzipHandler(ctx, c.next).ServeHTTP(rw, req)
2018-11-14 09:18:03 +00:00
}
}
func (c *compress) GetTracingInformation() (string, ext.SpanKindEnum) {
return c.name, tracing.SpanKindNoneEnum
}
2019-09-13 17:28:04 +00:00
func gzipHandler(ctx context.Context, h http.Handler) http.Handler {
2018-11-14 09:18:03 +00:00
wrapper, err := gziphandler.GzipHandlerWithOpts(
gziphandler.CompressionLevel(gzip.DefaultCompression),
gziphandler.MinSize(gziphandler.DefaultMinSize))
if err != nil {
2019-09-13 17:28:04 +00:00
log.FromContext(ctx).Error(err)
2018-11-14 09:18:03 +00:00
}
return wrapper(h)
}