forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
50 lines (42 loc) · 1.15 KB
/
gzip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package responsewriter
import (
"bufio"
"compress/gzip"
"fmt"
"io"
"net"
"net/http"
"reflect"
"strings"
)
type wrapWriter struct {
gzipResponseWriter
code int
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (g gzipResponseWriter) Write(b []byte) (int, error) {
return g.Writer.Write(b)
}
func Gzip(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
handler.ServeHTTP(w, r)
return
}
gz := gzip.NewWriter(w)
defer gz.Close()
gzw := &wrapWriter{gzipResponseWriter{Writer: gz, ResponseWriter: w}, http.StatusOK}
gzw.Header().Set("Content-Encoding", "gzip")
handler.ServeHTTP(gzw, r)
})
}
// Must implement Hijacker to properly chain with handlers expecting a hijacker handler to be passed
func (g *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := g.ResponseWriter.(http.Hijacker); ok {
return hijacker.Hijack()
}
return nil, nil, fmt.Errorf("Upstream ResponseWriter of type %v does not implement http.Hijacker", reflect.TypeOf(g.ResponseWriter))
}