-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
writerwrapper.go
285 lines (241 loc) · 6.71 KB
/
writerwrapper.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package gzip
import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/klauspost/compress/gzip"
)
// writerWrapper wraps the originalHandler
// to test whether to gzip and gzip the body if applicable.
type writerWrapper struct {
// header filter are applied by its sequence
Filters []ResponseHeaderFilter
// min content length to enable compress
MinContentLength int64
OriginWriter http.ResponseWriter
// use initGzipWriter() to init gzipWriter when in need
GetGzipWriter func() *gzip.Writer
// must close gzip writer and put it back to pool
PutGzipWriter func(*gzip.Writer)
// internal below
// *** WARNING ***
// *writerWrapper.Reset() method must be updated
// upon following field changing
// compress or not
// default to true
shouldCompress bool
// whether body is large enough
bodyBigEnough bool
// is header already flushed?
headerFlushed bool
responseHeaderChecked bool
statusCode int
// how many raw bytes has been written
size int
gzipWriter *gzip.Writer
bodyBuffer []byte
}
// interface guard
var _ http.ResponseWriter = (*writerWrapper)(nil)
var _ http.Flusher = (*writerWrapper)(nil)
func newWriterWrapper(filters []ResponseHeaderFilter, minContentLength int64, originWriter http.ResponseWriter, getGzipWriter func() *gzip.Writer, putGzipWriter func(*gzip.Writer)) *writerWrapper {
return &writerWrapper{
shouldCompress: true,
bodyBuffer: make([]byte, 0, minContentLength),
Filters: filters,
MinContentLength: minContentLength,
OriginWriter: originWriter,
GetGzipWriter: getGzipWriter,
PutGzipWriter: putGzipWriter,
}
}
// Reset the wrapper into a fresh one,
// writing to originWriter
func (w *writerWrapper) Reset(originWriter http.ResponseWriter) {
w.OriginWriter = originWriter
// internal below
// reset status with caution
// all internal fields should be taken good care
w.shouldCompress = true
w.headerFlushed = false
w.responseHeaderChecked = false
w.bodyBigEnough = false
w.statusCode = 0
w.size = 0
if w.gzipWriter != nil {
w.PutGzipWriter(w.gzipWriter)
w.gzipWriter = nil
}
if w.bodyBuffer != nil {
w.bodyBuffer = w.bodyBuffer[:0]
}
}
func (w *writerWrapper) Status() int {
return w.statusCode
}
func (w *writerWrapper) Size() int {
return w.size
}
func (w *writerWrapper) Written() bool {
return w.headerFlushed || len(w.bodyBuffer) > 0
}
func (w *writerWrapper) WriteHeaderCalled() bool {
return w.statusCode != 0
}
func (w *writerWrapper) initGzipWriter() {
w.gzipWriter = w.GetGzipWriter()
w.gzipWriter.Reset(w.OriginWriter)
}
// Header implements http.ResponseWriter
func (w *writerWrapper) Header() http.Header {
return w.OriginWriter.Header()
}
// Write implements http.ResponseWriter
func (w *writerWrapper) Write(data []byte) (int, error) {
w.size += len(data)
if !w.WriteHeaderCalled() {
w.WriteHeader(http.StatusOK)
}
if !w.shouldCompress {
w.WriteHeaderNow()
return w.OriginWriter.Write(data)
}
if w.bodyBigEnough {
return w.gzipWriter.Write(data)
}
// fast check
if !w.responseHeaderChecked {
w.responseHeaderChecked = true
header := w.Header()
for _, filter := range w.Filters {
w.shouldCompress = filter.ShouldCompress(header)
if !w.shouldCompress {
w.WriteHeaderNow()
return w.OriginWriter.Write(data)
}
}
if w.enoughContentLength() {
w.bodyBigEnough = true
w.WriteHeaderNow()
w.initGzipWriter()
return w.gzipWriter.Write(data)
}
}
if !w.writeBuffer(data) {
w.bodyBigEnough = true
// detect Content-Type if there's none
if header := w.Header(); header.Get("Content-Type") == "" {
header.Set("Content-Type", http.DetectContentType(w.bodyBuffer))
}
w.WriteHeaderNow()
w.initGzipWriter()
if len(w.bodyBuffer) > 0 {
written, err := w.gzipWriter.Write(w.bodyBuffer)
if err != nil {
err = fmt.Errorf("w.gzipWriter.Write: %w", err)
return written, err
}
}
return w.gzipWriter.Write(data)
}
return len(data), nil
}
func (w *writerWrapper) writeBuffer(data []byte) (fit bool) {
if int64(len(data)+len(w.bodyBuffer)) > w.MinContentLength {
return false
}
w.bodyBuffer = append(w.bodyBuffer, data...)
return true
}
func (w *writerWrapper) enoughContentLength() bool {
contentLength, err := strconv.ParseInt(w.Header().Get("Content-Length"), 10, 64)
if err != nil {
return false
}
if contentLength != 0 && contentLength >= w.MinContentLength {
return true
}
return false
}
// WriteHeader implements http.ResponseWriter
//
// WriteHeader does not really calls originalHandler's WriteHeader,
// and the calling will actually be handler by WriteHeaderNow().
//
// http.ResponseWriter does not specify clearly whether permitting
// updating status code on second call to WriteHeader(), and it's
// conflicting between http and gin's implementation.
// Here, gzip consider second(and furthermore) calls to WriteHeader()
// valid. WriteHeader() is disabled after flushing header.
// Do note setting status code to 204 or 304 marks content uncompressable,
// and a later status code change does not revert this.
func (w *writerWrapper) WriteHeader(statusCode int) {
if w.headerFlushed {
return
}
w.statusCode = statusCode
if !w.shouldCompress {
return
}
if statusCode == http.StatusNoContent ||
statusCode == http.StatusNotModified {
w.shouldCompress = false
return
}
}
// WriteHeaderNow Forces to write the http header (status code + headers).
//
// WriteHeaderNow must always be called and called after
// WriteHeader() is called and
// w.shouldCompress is decided.
//
// This method is usually called by gin's AbortWithStatus()
func (w *writerWrapper) WriteHeaderNow() {
if w.headerFlushed {
return
}
// if neither WriteHeader() or Write() are called,
// do nothing
if !w.WriteHeaderCalled() {
return
}
if w.shouldCompress {
header := w.Header()
header.Del("Content-Length")
header.Set("Content-Encoding", "gzip")
header.Add("Vary", "Accept-Encoding")
originalEtag := w.Header().Get("ETag")
if originalEtag != "" && !strings.HasPrefix(originalEtag, "W/") {
w.Header().Set("ETag", "W/"+originalEtag)
}
}
w.OriginWriter.WriteHeader(w.statusCode)
w.headerFlushed = true
}
// FinishWriting flushes header and closed gzip writer
//
// Write() and WriteHeader() should not be called
// after FinishWriting()
func (w *writerWrapper) FinishWriting() {
// still buffering
if w.shouldCompress && !w.bodyBigEnough {
w.shouldCompress = false
w.WriteHeaderNow()
if len(w.bodyBuffer) > 0 {
_, _ = w.OriginWriter.Write(w.bodyBuffer)
}
}
w.WriteHeaderNow()
if w.gzipWriter != nil {
w.PutGzipWriter(w.gzipWriter)
w.gzipWriter = nil
}
}
// Flush implements http.Flusher
func (w *writerWrapper) Flush() {
w.FinishWriting()
if flusher, ok := w.OriginWriter.(http.Flusher); ok {
flusher.Flush()
}
}