@@ -17,7 +17,7 @@ func (mw *gzipMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc {
17
17
// gzip support enabled
18
18
canGzip := strings .Contains (r .Header .Get ("Accept-Encoding" ), "gzip" )
19
19
// client accepts gzip ?
20
- writer := & gzipResponseWriter {w , false , canGzip }
20
+ writer := & gzipResponseWriter {w , false , canGzip , nil }
21
21
// call the handler with the wrapped writer
22
22
h (writer , r )
23
23
}
@@ -35,6 +35,7 @@ type gzipResponseWriter struct {
35
35
ResponseWriter
36
36
wroteHeader bool
37
37
canGzip bool
38
+ gzipWriter * gzip.Writer
38
39
}
39
40
40
41
// Set the right headers for gzip encoded responses.
@@ -96,9 +97,23 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) {
96
97
writer := w .ResponseWriter .(http.ResponseWriter )
97
98
98
99
if w .canGzip {
99
- gzipWriter := gzip .NewWriter (writer )
100
- defer gzipWriter .Close ()
101
- return gzipWriter .Write (b )
100
+ // Write can be called multiple times for a given response.
101
+ // (see the streaming example:
102
+ // https://github.com/ant0ine/go-json-rest-examples/tree/master/streaming)
103
+ // The gzipWriter is instantiated only once, and flushed after
104
+ // each write.
105
+ if w .gzipWriter == nil {
106
+ w .gzipWriter = gzip .NewWriter (writer )
107
+ }
108
+ count , errW := w .gzipWriter .Write (b )
109
+ errF := w .gzipWriter .Flush ()
110
+ if errW != nil {
111
+ return count , errW
112
+ }
113
+ if errF != nil {
114
+ return count , errF
115
+ }
116
+ return count , nil
102
117
}
103
118
104
119
return writer .Write (b )
0 commit comments