forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgzip.go
45 lines (37 loc) · 945 Bytes
/
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
package rest
import (
"compress/gzip"
"net/http"
"strings"
)
type gzipResponseWriter struct {
http.ResponseWriter
wroteHeader bool
}
func (self *gzipResponseWriter) WriteHeader(code int) {
self.Header().Set("Content-Encoding", "gzip")
self.ResponseWriter.WriteHeader(code)
self.wroteHeader = true
}
func (self *gzipResponseWriter) Write(b []byte) (int, error) {
if !self.wroteHeader {
self.WriteHeader(http.StatusOK)
}
gzipWriter := gzip.NewWriter(self.ResponseWriter)
defer gzipWriter.Close()
return gzipWriter.Write(b)
}
func (self *ResourceHandler) gzipWrapper(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// determine if gzip is needed
if self.EnableGzip == true &&
strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
writer := &gzipResponseWriter{w, false}
// call the handler
h(writer, r)
} else {
// call the handler
h(w, r)
}
}
}