@@ -26,8 +26,13 @@ func TestCompressor(t *testing.T) {
26
26
return w
27
27
})
28
28
29
- if len (compressor .encoders ) != 1 {
30
- t .Errorf ("nop encoder should be stored in the encoders map" )
29
+ var sideEffect int
30
+ compressor .SetEncoder ("test" , func (w io.Writer , _ int ) io.Writer {
31
+ return newSideEffectWriter (w , & sideEffect )
32
+ })
33
+
34
+ if len (compressor .encoders ) != 2 {
35
+ t .Errorf ("nop and test encoders should be stored in the encoders map" )
31
36
}
32
37
33
38
r .Use (compressor .Handler )
@@ -47,6 +52,11 @@ func TestCompressor(t *testing.T) {
47
52
w .Write ([]byte ("textstring" ))
48
53
})
49
54
55
+ r .Get ("/getimage" , func (w http.ResponseWriter , r * http.Request ) {
56
+ w .Header ().Set ("Content-Type" , "image/png" )
57
+ w .Write ([]byte ("textstring" ))
58
+ })
59
+
50
60
ts := httptest .NewServer (r )
51
61
defer ts .Close ()
52
62
@@ -93,6 +103,12 @@ func TestCompressor(t *testing.T) {
93
103
acceptedEncodings : []string {"nop, gzip, deflate" },
94
104
expectedEncoding : "nop" ,
95
105
},
106
+ {
107
+ name : "test is used and side effect is cleared after close" ,
108
+ path : "/getimage" ,
109
+ acceptedEncodings : []string {"test" },
110
+ expectedEncoding : "" ,
111
+ },
96
112
}
97
113
98
114
for _ , tc := range tests {
@@ -107,7 +123,10 @@ func TestCompressor(t *testing.T) {
107
123
}
108
124
109
125
})
126
+ }
110
127
128
+ if sideEffect > 1 {
129
+ t .Errorf ("side effect should be cleared after close" )
111
130
}
112
131
}
113
132
@@ -217,3 +236,26 @@ func decodeResponseBody(t *testing.T, resp *http.Response) string {
217
236
218
237
return string (respBody )
219
238
}
239
+
240
+ type (
241
+ sideEffectWriter struct {
242
+ w io.Writer
243
+ s * int
244
+ }
245
+ )
246
+
247
+ func newSideEffectWriter (w io.Writer , sideEffect * int ) io.Writer {
248
+ * sideEffect = * sideEffect + 1
249
+
250
+ return & sideEffectWriter {w : w , s : sideEffect }
251
+ }
252
+
253
+ func (w * sideEffectWriter ) Write (p []byte ) (n int , err error ) {
254
+ return w .w .Write (p )
255
+ }
256
+
257
+ func (w * sideEffectWriter ) Close () error {
258
+ * w .s = * w .s - 1
259
+
260
+ return nil
261
+ }
0 commit comments