bump go-pkgz/rest

This commit is contained in:
Umputun
2021-04-04 02:39:42 -05:00
parent 1fec95e9b8
commit 7a263fed42
7 changed files with 61 additions and 16 deletions

View File

@@ -4,5 +4,5 @@ go 1.15
require (
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.6.1
github.com/stretchr/testify v1.7.0
)

View File

@@ -8,6 +8,8 @@ github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=

View File

@@ -9,6 +9,17 @@ import (
"sync"
)
var gzDefaultContentTypes = []string{
"text/css",
"text/javascript",
"text/xml",
"text/html",
"text/plain",
"application/javascript",
"application/x-javascript",
"application/json",
}
var gzPool = sync.Pool{
New: func() interface{} { return gzip.NewWriter(ioutil.Discard) },
}
@@ -28,21 +39,51 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
}
// Gzip is a middleware compressing response
func Gzip(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
func Gzip(contentTypes ...string) func(http.Handler) http.Handler {
gzCts := gzDefaultContentTypes
if len(contentTypes) > 0 {
gzCts = contentTypes
}
contentType := func(r *http.Request) string {
result := r.Header.Get("Content-type")
if result == "" {
return "application/octet-stream"
}
return result
}
w.Header().Set("Content-Encoding", "gzip")
f := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
var gzOk bool
ctype := contentType(r)
for _, c := range gzCts {
if strings.EqualFold(ctype, c) {
gzOk = true
break
}
}
gz.Reset(w)
defer gz.Close()
if !gzOk {
next.ServeHTTP(w, r)
return
}
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
})
w.Header().Set("Content-Encoding", "gzip")
gz := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(w)
defer gz.Close()
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
})
}
return f
}