2021-04-25 10:30:15 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"compress/gzip"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
var gzPool = sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
w := gzip.NewWriter(ioutil.Discard)
|
|
|
|
return w
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
type gzipResponseWriter struct {
|
|
|
|
io.Writer
|
|
|
|
http.ResponseWriter
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *gzipResponseWriter) WriteHeader(status int) {
|
|
|
|
w.Header().Del("Content-Length")
|
|
|
|
w.ResponseWriter.WriteHeader(status)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
|
|
|
|
return w.Writer.Write(b)
|
|
|
|
}
|
|
|
|
|
2021-05-26 19:40:04 +00:00
|
|
|
// Gzip middleware for HTTP Handler
|
2021-04-25 10:30:15 +00:00
|
|
|
func Gzip(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
|
|
|
|
|
|
gz := gzPool.Get().(*gzip.Writer)
|
|
|
|
defer gzPool.Put(gz)
|
|
|
|
|
|
|
|
gz.Reset(w)
|
|
|
|
defer gz.Close()
|
|
|
|
|
|
|
|
next(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
|
|
|
|
}
|
|
|
|
}
|