2021-09-13 00:39:09 +02:00
|
|
|
package handler
|
2020-09-06 06:55:01 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
var gzPool = sync.Pool{
|
|
|
|
New: func() interface{} {
|
2021-12-03 07:44:17 +01:00
|
|
|
return gzip.NewWriter(io.Discard)
|
2020-09-06 06:55:01 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
type gzipResponseWriter struct {
|
|
|
|
io.Writer
|
|
|
|
http.ResponseWriter
|
|
|
|
}
|
|
|
|
|
2020-12-13 23:24:16 +01:00
|
|
|
// WriteHeader sends an HTTP response header with the provided status code.
|
|
|
|
// It also deletes the Content-Length header, since the GZIP compression may modify the size of the payload
|
2020-09-06 06:55:01 +02:00
|
|
|
func (w *gzipResponseWriter) WriteHeader(status int) {
|
|
|
|
w.Header().Del("Content-Length")
|
|
|
|
w.ResponseWriter.WriteHeader(status)
|
|
|
|
}
|
|
|
|
|
2020-12-13 05:32:26 +01:00
|
|
|
// Write writes len(b) bytes from b to the underlying data stream.
|
2020-09-06 06:55:01 +02:00
|
|
|
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
return w.Writer.Write(b)
|
|
|
|
}
|
|
|
|
|
2021-01-28 00:25:37 +01:00
|
|
|
// GzipHandler compresses the response of a given http.Handler if the request's headers specify that the client
|
2020-10-23 22:29:20 +02:00
|
|
|
// supports gzip encoding
|
2020-09-06 06:55:01 +02:00
|
|
|
func GzipHandler(next http.Handler) http.Handler {
|
2021-01-28 00:25:37 +01:00
|
|
|
return GzipHandlerFunc(func(writer http.ResponseWriter, r *http.Request) {
|
|
|
|
next.ServeHTTP(writer, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// GzipHandlerFunc compresses the response of a given http.HandlerFunc if the request's headers specify that the client
|
|
|
|
// supports gzip encoding
|
|
|
|
func GzipHandlerFunc(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(writer http.ResponseWriter, r *http.Request) {
|
2020-09-06 06:55:01 +02:00
|
|
|
// If the request doesn't specify that it supports gzip, then don't compress it
|
|
|
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
|
|
|
next.ServeHTTP(writer, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
writer.Header().Set("Content-Encoding", "gzip")
|
|
|
|
gz := gzPool.Get().(*gzip.Writer)
|
|
|
|
defer gzPool.Put(gz)
|
|
|
|
gz.Reset(writer)
|
|
|
|
defer gz.Close()
|
|
|
|
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: writer, Writer: gz}, r)
|
2021-01-28 00:25:37 +01:00
|
|
|
}
|
2020-09-06 06:55:01 +02:00
|
|
|
}
|