forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
72 lines (58 loc) · 1.55 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package rest
import (
"compress/gzip"
"net/http"
"strings"
)
type gzipResponseWriter struct {
http.ResponseWriter
wroteHeader bool
canGzip bool
}
func (self *gzipResponseWriter) WriteHeader(code int) {
// always set the Vary header, even if this particular request
// is not gzipped.
self.Header().Add("Vary", "Accept-Encoding")
if self.canGzip {
self.Header().Set("Content-Encoding", "gzip")
}
self.ResponseWriter.WriteHeader(code)
self.wroteHeader = true
}
func (self *gzipResponseWriter) Flush() {
if !self.wroteHeader {
self.WriteHeader(http.StatusOK)
}
flusher := self.ResponseWriter.(http.Flusher)
flusher.Flush()
}
func (self *gzipResponseWriter) CloseNotify() <-chan bool {
notifier := self.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
func (self *gzipResponseWriter) Write(b []byte) (int, error) {
if !self.wroteHeader {
self.WriteHeader(http.StatusOK)
}
if self.canGzip {
gzipWriter := gzip.NewWriter(self.ResponseWriter)
defer gzipWriter.Close()
return gzipWriter.Write(b)
}
return self.ResponseWriter.Write(b)
}
func (self *ResourceHandler) gzipWrapper(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if self.EnableGzip == true {
// gzip support enabled
canGzip := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")
// client accepts gzip ?
writer := &gzipResponseWriter{w, false, canGzip}
// call the handler with the wrapped writer
h(writer, r)
} else {
// gzip support disabled, don't do anything
h(w, r)
}
}
}